The Stored Procedure InsertCustomerWithTransaction
The Stored Procedure InsertCustomerWithTransaction
Figure 10-31
Now we will write a stored procedure that inserts data for a new customer, records a purchase,
and creates an entry in the CUSTOMER_ARTIST_INT table. We will name this stored proce-
Running the
InsertCustomerAndInterests
dure InsertCustomerWithTransaction, and the necessary SQL code is shown in Figure 10-32.
Stored Procedure The Execute button
The Parse button The SQL statement
to run the stored procedure
The output from running the stored procedure
The Stored Procedures folder object
The
dbo.InsertCustomerAndInterests
stored procedure object
Part 4 Multiuser Database Processing
Figure 10-32
The SQL Statements for the InsertCustomerWithTransaction Stored Procedure
Chapter 10 Managing Databases with SQL Server 2008 R2
Figure 10-32
Continued (continued)
This procedure receives seven parameters having data about the new customer and about the customer’s purchase. We will use this procedure to discuss transaction processing in SQL Server 2008 R2.
The first action is to see whether the customer already exists. If so, the procedure exits with an error message. If the customer does not exist, this procedure then starts a transaction with the Transact-SQL BEGIN TRANSACTION command. Recall from Chapter 9 that transactions ensure that all of the database activity is committed atomically; either all of the updates occur or none of them do. The transaction begins, and the new customer row is inserted. The new value of CustomerID is obtained, as shown in the InsertCustomerWithInterests stored procedure. Next, the procedure checks to determine whether ArtistID, WorkID, and TransactionID are valid. If any are invalid, the transaction is rolled back using the Transact-SQL ROLLBACK TRANSACTION command.
Part 4 Multiuser Database Processing
Figure 10-32
Continued
If all the surrogate key values are valid, two actions in the transaction are completed. First, an UPDATE statement updates DateSold, SalesPrice, and CustomerID in the appropri- ate TRANS row. DateSold is set to system date via the Transact-SQL GETDATE( ) function, SalesPrice is set to the value of @TransSalesPrice, and CustomerID is set to the value of @CustomerID. Second, a row is added to CUSTOMER_ARTIST_INT to record the customer’s interest in this artist.
If everything proceeds normally to this point, the transaction is committed using the Transact-SQL COMMIT TRANSACTION command. After, and only after, the transaction is committed, we print the results messages.
To create the InsertCustomerWithTransaction stored procedure in the VRG database, add the SQL code in Figure 10-32 to your DBP-e12-VRG-Create-Stored-Procedures.sql script. Include a comment to separate the code sections in this script file. Use the highlighting technique described in the preceding By the Way feature to parse and execute the SQL code.
Chapter 10 Managing Databases with SQL Server 2008 R2
To use the InsertCustomerWithTransaction stored procedure, we will record the following purchase by our next new customer, Melinda Gliddens, who just bought a print of John Singer Sargent’s Spanish Dancer for $350.00. The SQL statement is:
/* *** SQL-EXEC-CH10-02 *** */ EXEC InsertCustomerWithTransaction
@NewCustomerLastName = 'Gliddens', @NewCustomerFirstName = 'Melinda', @NewCustomerAreaCode = '360', @NewCustomerPhoneNumber = '765-8877', @NewCustomerEmail = '[email protected]', @ArtistLastName = 'Sargent', @WorkTitle = 'Spanish Dancer', @WorkCopy = '588/750', @TransSalesPrice = 350.00;
To execute this EXEC InsertCustomerWithTransaction statement, add the SQL statement to your VRG-Create-Stored-Procedures.sql script. Include a comment to separate the new SQL statement. Use the highlighting technique described in the preceding By the Way feature to parse and execute the SQL statement. Figure 10-33 shows the invocation of this procedure using sample data.
If we now look at the SQL code that has actually been stored for these two stored procedures (by right-clicking the stored procedure object and
then choosing Modify), we will find that SQL Server has added the following lines before the code we wrote:
USE [VRG] GO /****** Object: StoredProcedure [ {StoredProcedureName} ]
Script Date: {Date and Time created or altered} ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO
The Transact-SQL USE [ {DatabaseName} ] command tells the stored proce- dure to use the VRG database when it is called. This is the SQL command equivalent of selecting the database name in the Available Databases drop-down list in the Microsoft SQL Server Management Studio.
The Transact-SQL SET ANSI_NULLS ON command specifies how SQL server handles comparisons of NULL values using equals (=) and not equals (<>) (for more information, see http://msdn.microsoft.com/en-us/library/ms188048.aspx).
The Transact-SQL SET QUOTED_IDENTIFIER ON command specifies that object identifiers (table names, column names, etc.) can be enclosed in double quotes (”), which allows the use of SQL reserved words as objects names. For example, we could run the SQL statement:
/* *** EXAMPLE CODE - DO NOT RUN *** */ SELECT "Select" FROM
"FROM" WHERE
"Where" = 'San Francisco';
Note that literals (San Francisco in this example) are still enclosed in single quotes. For more information, see http://msdn.microsoft.com/en-us/library/ms174393.aspx.
(continued )
Part 4 Multiuser Database Processing
Finally, the GO command is not a Transact-SQL statement, but rather a command used by the Microsoft SQL Server Management Studio (and other SQL utilities) to mark the end of a batch of commands so that the utility can process sections of the code (as marked by the GO commands) separately instead of all at once. Declared variables (@RowCount) only exist within a section of code delineated by the GO statement and are
Figure 10-33
cleared after that group of statements is run. For more information, see http://msdn. Running the
microsoft.com/en-us/library/ms188037.aspx.
InsertCustomerWith Transaction Stored Procedure
The Execute button The Parse button
The SQL statement to run the stored procedure
The output from running the stored procedure
The Stored Procedures folder object
The
dbo.InsertCustomerWithTransaction
stored procedure object