The Stored Procedure InsertCustomerAndInterests

The Stored Procedure InsertCustomerAndInterests

In our preceding discussion of Transact-SQL, we used as our example the need to enter data for a new customer and the artists of interest to that customer. The code segments we wrote were very specifically tied to the data we used, and thus of limited use. Is there a way to write a general block of code that could be used for more than one customer? Yes, and that block of code is a stored procedure.

Figure 10-30 shows the SQL code for the InsertCustomerAndInterests stored procedure. This stored procedure generalizes our previous code and can be used to insert data for any new customer into CUSTOMER, and then store data for that customer in CUSTOMER_ARTIST_INT, linking the customer to all artists having a particular nationality.

Five parameters are input to the procedure: @NewLastName, @NewFirstName, @NewAreaCode, @NewPhoneNumber, and @Nationality. The first four parameters are the new customer data, and the fourth one is the nationality of the artists for which the new customer has an interest. The stored procedure also uses three variables: @RowCount, @ArtistID, and @CustomerID. These variables are used to store values of the number of the row, the value of the ArtistID primary key, and the value of the CustomerID primary key, respectively.

The first task performed by this stored procedure is to determine whether the customer already exists. If the value of @RowCount in the first SELECT statement is greater than zero, then a row for that customer already exists. In this case, nothing is done, and the stored procedure prints an error message and exits (using the RETURN command). As stated earlier, the error message is visible in the Microsoft SQL Server Management Studio, but it generally would not be visible to application programs that invoked this procedure. Instead, a parameter or other facility needs to be used to return the error message back to the user via the application program. Discussion of that topic is beyond the scope of the present discussion, but we will send message back to the Microsoft SQL Server Management Studio to mimic such actions and provide a means to make sure our stored procedures are working correctly.

If the customer does not already exist, the procedure inserts the new data into the table dbo.CUSTOMER and then a new value of CustomerID is read into the variable @CustomerID. Internally, SQL Server adds a prefix to the table name that shows the name of the user who created it. Here, the prefix dbo is used to ensure that the CUSTOMER table created by the database owner (dbo) is processed. Without the dbo prefix, if the user invoking the stored procedure had created a table named CUSTOMER, then the user’s table and not the dbo’s table would be used.

The purpose of the second SELECT in Figure 10-30 is to obtain the value of the surrogate key CustomerID that was created by the INSERT statement. Another option is to use the Transact- SQL @@Identity function, which provides the value of the most recently created surrogate key value. Using this function, you could replace the second SELECT statement with the expression:

SET @CustomerID = @@Identity

Chapter 10 Managing Databases with SQL Server 2008 R2

Figure 10-30

The SQL Statements for the InsertCustomerAndInterests Stored Procedure

(continued)

Part 4 Multiuser Database Processing

Figure 10-30

To create the appropriate intersection table rows, an SQL cursor named ArtistCursor is

Continued

created on an SQL statement that obtains all ARTIST rows where Nationality equals the parameter @Nationality. The cursor is opened and positioned on the first row by calling FETCH NEXT, and then the cursor is processed in a WHILE loop. In this loop, statements between BEGIN and END are iterated until SQL Server signals the end of the data by setting the value of the SQL Server function @@FETCH_STATUS to zero. Upon each iteration of the WHILE loop, a new row is inserted into the intersection table CUSTOMER_ ARTIST_INT. The FETCH NEXT statement at the end of the block moves the cursor to the next row.

To create the InsertCustomerAndInterests stored procedure in the VRG database, create

a new SQL script named DBP-e12-VRG-Create-Stored-Procedures.sql containing the SQL code in Figure 10-30. Include a beginning comments section similar to the one shown in Figure 10-13. Use the Parse button to check your SQL code, and after it parses correctly save the completed code before running it. Finally, check to make sure that the VRG database is selected in the Available Databases list, and then use the Execute button to create the stored procedure.

To invoke the InsertCustomerAndInterests stored procedure for Michael Bench, we use the following SQL statement:

/* *** SQL-EXEC-CH10-01 *** */ EXEC InsertCustomerAndInterests

@NewLastName = 'Bench', @NewFirstName = 'Michael', @NewAreaCode = '206', @NewPhoneNumber = '876-8822', @NewEmail = '[email protected]', @Nationality = 'French';

Before we test any new functionality of a database, such as a stored procedure or a trigger, it is always a good idea to refresh the content of

the database in Microsoft SQL Server Management Studio. This can be done by using the Refresh command in the object shortcut menu. For example, after creating the

Chapter 10 Managing Databases with SQL Server 2008 R2

InsertCustomerAndInterests stored procedure, right-click the VRG Stored Procedures folder in the Programmability folder and then click the Refresh command. Then expand the Stored Procedures folder and make sure the stored procedure object (shown as dbo.InsertCustomerWithInterests) is visible before running any test data.

Figure 10-31 shows the execution of the stored procedure in the SQL Server Management Studio. Notice how our sections of PRINT commands have produced the necessary output so that we can see what actions were taken. If we now wanted to check the tables themselves, we could do so, but that is not necessary at this point. In the output in Figure 10-31, we see that customer Michael Bench has been added to the CUSTOMER table and that new rows (a total of two, although we would have to scroll through the output to see that there are no more than two) have been inserted into the CUSTOMER_ARTIST_INT table.

You can include the preceding EXEC InsertCustomerAndInterests statement in your DBP-e12-VRG-Create-Stored-Procedures.sql script and

run it from there using the highlighting technique we illustrated in the section on SQL views. There we noted that when there are multiple SQL statements in an open SQL script file, you can still run them one at a time by highlighting just the SQL statement or statements that you want to use. The Microsoft SQL Server Management Studio will then only apply actions such as parsing (using the Parse button) and executing (using the Execute button) to the highlighted SQL statement or statements.

This is a good trick to know, because it allows you to store multiple SQL state- ments (e.g., a set of queries) in one SQL script for convenience but still control which statements are actually executed. Even better, if you highlight more than one SQL statement, then the highlighted set of commands can be controlled the same way.