Chapter 8: Developing Database Applications with ADO 319 error handler is fired, enabling you to trap and respond to run-time errors. This tight integration with Visual Basic makes it easy to handle ADO errors. The following ShowError subroutine illustrates how ADO’s error handling can be integrated with Visual Basic’s On Error function: Private Sub ShowError(cn As ADODB.Connection) Dim rs As New ADODB.Recordset On Error GoTo ErrorHandler rs.Open "Select * From no_such_table", cn rs.Close Exit Sub ErrorHandler: DisplayADOError cn End Sub Here, the ShowError function attempts to open a Recordset object against a nonexistent table. At the beginning of this function, the On Error statement enables Visual Basic’s error handler. In this case, the On Error statement causes the program to branch to the ErrorHandler label when a trappable error is encountered. Executing the Open method with a nonexisting table causes the ADO object framework to generate a run-time error, which, in turn, causes the program execution to resume with the first statement following the label. In this example, the DisplayADOError subroutine is executed following the invalid Open attempt. The following code listing shows how the DisplayDAOError subroutine uses DAO’s Error object and Errors collection to display information about an ADO error condition in a simple message box: Private Sub DisplayADOError(cn As ADODB.Connection) Dim er As ADODB.Error For Each er In cn.Errors MsgBox "Number: " & er.Number & vbCrLf & _ "Source: " & er.Source & vbCrLf & _ "Text: " & er.Description Next End Sub 320 Microsoft SQL Server 2005 Developer’s Guide In this subroutine, an ADO Connection object is passed in as a parameter. The ADO Errors collection is contained in the Connection object. Next, a new ADO Error object named er is declared, and a For Each loop iterates through the ADO Errors collection. The loop is required because the ADODB Errors collection can contain multiple Error objects where each Error object represents a different error condition. With the For Each loop, the values of the Number, Source, and Description properties are displayed in a message box. The Number property of the ADO Error object contains the ADO error message number, while the Source property identifies the source object that fired the error. As you might expect, the Description property contains the error condition’s text description. Figure 8-17 shows the message box that the DisplayADOError subroutine displays. Advanced Database Functions Using ADO You’ve now seen how to use the basic ADO Connection, Recordset, and Command objects to query and update the SQL Server database. In this section, you see how to use some of the more advanced ADO functions, such as how to perform updates with batch cursors and commit and roll back transactions. Batch Updates Batch updates allow all the changes made to a Recordset object to be written back to the data source all at once. Batch updates are most useful when you are working with disconnected Recordset sets such as you might use in Web-based applications. With batch updates, the Recordset object is updated using the normal AddNew, Update, and Delete methods. After all the changes have been made to the Recordset object, the BatchUpdate method is used to post the entire batch of changes to the database. The client Batch cursor library generates a SQL query to synchronize the Figure 8-17 ADO error handling Chapter 8: Developing Database Applications with ADO 321 local Recordset object and the data on the remote SQL Server system. The following example illustrates how to use the ADO Recordset object’s BatchUpdate method: Private Sub BatchUpdate(cn As ADODB.Connection) Dim rs As New ADODB.Recordset Dim i As Integer 'Pass in the SQL, Connection, Cursor type, ' lock type and source type rs.Open "Select Dep_ID, Dep_Name From Sales.SalesDepartment", _ cn, adOpenKeyset, adLockBatchOptimistic, adCmdText 'Add 50 rows to the Sales.SalesDepartment table For i = 1 To 50 rs.AddNew rs!Dep_ID = i rs!Dep_Name = "Add Batch Department " & CStr(i) rs.Update Next rs.UpdateBatch 'Display the new rows in a grid DisplayKeysetGrid rs, Grid, 1 rs.Close End Sub This code is much like the standard ADO cursor update example presented earlier in this chapter in the section “Updating Rows with a Recordset.” However, one important difference exists. The Recordset object’s lock type parameter is assigned the constant adLockBatchOptimistic. This tells ADO the Recordset object will use a batch cursor. After the Recordset object is opened, the AddNew and Update methods are used to add 50 rows to the local Recordset. Important to note is that unlike a standard keyset cursor, which immediately propagates the new rows to the data source, the batch cursor doesn’t update the data source until the UpdateBatch method executes. Then all the updated rows are written to the base tables. TIP The CancelBatch method can be used to cancel all the pending changes that would be performed by an UpdateBatch operation. 322 Microsoft SQL Server 2005 Developer’s Guide Using Transactions Transactions enable you to group together multiple operations that can be performed as a single unit of work. This helps to ensure database integrity. For instance, transferring funds from your savings account to your checking account involves multiple database operations, and the transfer cannot be considered complete unless all the operations are successfully completed. A typical transfer from your savings account to your checking account requires two separate, but related, operations: a withdrawal from your savings account and a deposit to your checking account. If either operation fails, the transfer is not completed. Therefore, both these functions are considered part of the same logical transaction. In this example, both the withdrawal and the deposit would be grouped together as a single transaction. If the withdrawal operation succeeded, but the deposit failed, the entire transaction could be rolled back, restoring the database to the condition it had before the withdrawal operation was attempted. SQL Server supports transactions, but not all databases do. Rolling Back Transactions In ADO, transactions are enabled in the Connection object. The Connection object’s RollbackTrans method can be used to restore the database to the state it was in before the transaction occurred. The following example shows how to use the RollbackTrans method: Private Sub TransRollBack(cn As ADODB.Connection) Dim rs As New ADODB.Recordset 'Start a transaction using the existing Connection object cn.BeginTrans 'Execute SQL to delete all of the rows from the table cn.Execute "Delete Sales.SalesDepartment" 'Now Rollback the transaction - the table is unchanged cn.RollbackTrans 'Create a recordset to display the unchanged table rs.Open "Select * From Sales.SalesDepartment", cn, , , adCmdText DisplayForwardGrid rs, Grid rs.Close End Sub In this example, executing the BeginTrans method of the Connection object named cn signals to the database that a transaction is about to begin. Then the Chapter 8: Developing Database Applications with ADO 323 Connection object’s Execute method is used to issue a SQL Delete statement that deletes all the rows in the Sales.SalesDepartment table. Instead of committing that change to the database, however, the Connection object’s RollbackTrans method is used to undo the transaction, restoring the original contents of the Sales. SalesDepartment table. A rollback would also be performed if a network failure or system crash prevented the Commit from being successfully executed. A Recordset object is created and displayed to illustrate that the table’s contents were unchanged after the RollBackTrans method. TIP SQL Server maintains database modifications in a transaction log file, which contains a serial record of all the modifications that have been made to a database. The transaction log contains both before and after images of each transaction. Committing Transactions When a transaction is successfully completed, the Connection object’s CommitTrans method writes the transaction to the database. In the following example, you see how to use ADO to begin a transaction and then commit that transaction to the SQL Server database: Private Sub TransCommit(cn As ADODB.Connection) Dim rs As New ADODB.Recordset 'Start a transaction using the existing Connection object cn.BeginTrans 'Execute SQL to delete all of the rows from the table cn.Execute "Delete Sales.SalesDepartment" 'Commit the transaction and update the table cn.CommitTrans 'Create a recordset to display the empty table rs.Open "Select * From Sales.SalesDepartment", cn, , , adCmdText DisplayForwardGrid rs, Grid rs.Close End Sub Again, executing the BeginTrans method of the Connection object signals to the database that a transaction is about to begin, and the Execute method is used to issue a SQL Delete statement. This time, however, the changes are committed to the 324 Microsoft SQL Server 2005 Developer’s Guide database using the Connection object’s CommitTrans method. Finally, a Recordset object is opened to illustrate that the table’s contents were deleted following the CommitTrans method. Summary While ADO provides similar functionality to both the older DAO and RDO object frameworks, ADO’s more-flexible object model allows it to be used effectively for a wider range of applications. The DAO object model was primarily designed around the Jet engine, and the RDO object model was primarily designed for ODBC data access; however, the ADO object model was built around OLE DB. Unlike Jet and ODBC, which are both geared toward database access, OLE DB is intended to provide heterogeneous data access to a number of different data sources. OLE DB provides access to a variety of data sources, including Excel spreadsheets, Active Directory, and Exchange, in addition to relational databases such as SQL Server. Bear in mind that ADO is best suited for maintaining older COM-based applications. Microsoft recommends that all new SQL Server 2005 applications be written using ADO.NET and the .NET Framework as you saw in Chapter 7. 325 CHAPTER 9 Reporting Services IN THIS CHAPTER Reporting Services Architecture Report Server Report Manager Reporting Services Configuration and Management Tools Report Authoring Tools Programmability Accessing Reports Report Authoring Copyright © 2006 by The McGraw-Hill Companies. Click here for terms of use. 326 Microsoft SQL Server 2005 Developer’s Guide O ne of the most exciting enhancements found in SQL Server 2005 is Reporting Services. Reporting Services was first introduced as an add-on to SQL Server 2000 and provided customers with a comprehensive reporting platform. Because SQL Server has always been an easy-to-implement relational database platform, it has been very popular for department-level implementations as well as a database platform for small and medium-sized businesses. However, SQL Server had no built-in tools that were capable of generating reports, so many companies started using desktop reporting tools like Microsoft Access. Many medium- and larger-sized organizations adopted more powerful third-party reporting products such as Business Object’s Crystal Reports. The inclusion of Reporting Services in SQL Server 2005 has changed all of that. Reporting Services is a server-based reporting service that goes beyond the capabilities of simple reporting solutions like Access. Reporting Services provides an extensive environment for designing, managing, and deploying reports to local departments or the entire organization. You can build reports based on relational or multidimensional data from SQL Server, Analysis Services, any Microsoft .NET data provider such as ODBC or OLE DB, or even Oracle. You can create ad hoc reports that use predefined models and data sources, or create tabular, matrix, and free-form reports. Reporting Services not only provides the ability to graphically design reports but also enables you to securely deploy those reports across the enterprise rendered in a variety of different formats, including Web-based HTML reports, Windows- based rich client reports, and reports rendered for mobile devices. In the first part of this chapter, you’ll get an overview of the architecture used by SQL Server 2005’s Reporting Services. In the second part of this chapter, you get a look at how you design reports using the report designer and report wizard. Then you see how to manage and deploy reports using Reporting Services. Reporting Services Architecture SQL Server 2005’s Reporting Services isn’t just a report design tool. Instead, it’s a complete reporting platform that enables the creation of reports, stores report definitions, provides secure access to reports, renders reports in a variety of different output formats, schedules report delivery, enables the deployment of those reports, and allows for programmability and extensibility features. Reporting Services provides a middle-tier server that runs under IIS (Internet Information Services). If IIS is not present on the system running the installation, Chapter 9: Reporting Services 327 the option to install Reporting Services will not be present on SQL Server 2005’s installation dialogs. While Reporting Services can be installed on the same server system as the SQL Server database engine, for improved scalability it’s usually better to install Reporting Services on a separate server. NOTE Reporting Services is licensed as a part of SQL Server 2005 and does not require any separate licensing for use on a single system. However, it does require an additional license if you implement it on a separate system. SQL Server 2005 Reporting Services includes several applications. It’s a server-based subsystem that’s designed to enable the creation, management, and deployment of reports across the enterprise. You can see an overview of the Reporting Service architecture shown in Figure 9-1. Reporting Services Components As you can see in Figure 9-1, Reporting Services consists of a variety of interrelated components. These components include processing components, graphical and command-prompt tools, and programmatic interfaces that facilitate development of reports in a managed environment. Report Designer Report Builder Reporting Services Database Reporting Services Reporting Manager HTML Excel Web Archive PDF TIFF CSV XML IIS Report Server Data Sources Figure 9-1 Reporting Services architecture 328 Microsoft SQL Server 2005 Developer’s Guide Report Server The Report Server is the core component in Reporting Services. The Report Server processes report requests and renders reports in the desired output format. Report Server functions also include processing of report models, distribution of reports, security enforcement, and controlling user access to items and operations. Report Manager The Report Manager is a Web-based application that enables the DBA or reporting administrator to control the security and overall management attributes of the reports created using Reporting Services. The Report Manager is used to specify report change authority as well as report access authority. It can also be used to set up delivery schedules for Reporting Services reports. Reporting Services Configuration and Management Tools Reporting Services includes two configuration tools you can use to configure, deploy, upgrade, and manage local or remote report server instances: ᭤ The Reporting Services Confi guration tool ᭤ The Report Server command-prompt utilities Report Authoring Tools Reporting Services includes several tools for creating, publishing, and managing reports. ᭤ The Report Designer ᭤ The Report Model Designer ᭤ The Report Builder The Report Designer enables you to visually design reports as well as control their deployment and is accessed through the Business Intelligence (BI) Development Studio. The Report Model Designer is the tool used to describe the metadata from a data source that is incorporated into ad hoc reports. The Report Builder then uses the report model definitions created with the Report Model Designer to generate a query to retrieve the requested data, and create and publish the report. . 326 Microsoft SQL Server 2005 Developer’s Guide O ne of the most exciting enhancements found in SQL Server 2005 is Reporting Services. Reporting Services was first introduced as an add-on to SQL. environment. Report Designer Report Builder Reporting Services Database Reporting Services Reporting Manager HTML Excel Web Archive PDF TIFF CSV XML IIS Report Server Data Sources Figure 9-1 Reporting Services architecture 328 Microsoft SQL Server 2005 Developer’s Guide Report Server The Report Server is the. and the Execute method is used to issue a SQL Delete statement. This time, however, the changes are committed to the 324 Microsoft SQL Server 2005 Developer’s Guide database using the Connection