Uploaded by Kevin Sims

SQL Level I Lesson 12

advertisement
9/28/12
S Q L Lev el I: Lesson 12
SQL Level I: Lesson 12 (printer-friendly version)
Your Instructor: Cecelia Allison
INSTRUCTIONS:
To print this page, wait for the page to fully load. Once the document is ready to print, simply click your
browser's File menu and choose Print .
To save this page, click your browser's File menu and choose Save As. Select a disk drive and folder to
receive the file, and change the name of the file to less12.htm. To view the file while you are offline, just go to
the drive and folder you selected when you saved the file and double-click the file named less12.htm. Your
browser will start and you will have access to the file.
Chapter 1
Introduction
Do you believe that you have finally arrived at your last lesson in my course? In your final lesson, I will explain how
stored procedures, triggers, and cursors are used in SQL. You will learn how to create and execute a stored
procedure and how to create a trigger. You will also learn how to declare, fetch, close, and deallocate a cursor.
I will define new terms associated with stored procedures, triggers, and cursors, and we'll revisit Janet Stevens to
provide additional examples. By the end of this lesson, you'll understand how to implement advanced manipulation
techniques in SQL.
I also will recap some of the information you have learned up to now!
Enjoy!
Chapter 2
Stored Procedures
Janet wants to store frequently used complex queries in the database. To accomplish this, she creates stored
procedures.
Stored Procedures: Explanations and Definitions
Key Terms
compile. Converting program commands into a set of instructions that the computer can understand.
CREATE PROCEDURE. Used to create a new procedure.
declaration. Identifying all variables that will be used in the stored procedure.
EXECUTE. Used to run a stored procedure. Parameters that need to be passed to the procedure must be specified
within the EXECUTE statement.
input parameter. Used to accept input from the user.
https://w w w .ed2go.com/C lassroom/P rintLesson.aspx?classroom=fTA IgP gRM ZkDIp99pM 6pBllQ lm8v G P …
9/28/12
S Q L Lev el I: Lesson 12
local variable. Used to store values located within a stored procedure.
PRINT Statement. Used to display data to an output device.
RETURN statement. Used to return results from functions.
stored procedure. One or more SQL statements stored inside a database.
Stored procedures can be complex because they enable you to create and store complied code. They need to be
compiled only once. When programs are stored already compiled, it optimizes the performance of your queries
because the database doesn't have to do as much work when you get ready to process the code.
Stored procedures are primarily used to simplify complex queries, optimize the performance of SQL queries, and
improve security.
Note: Stored procedures are database specific, so check your DBMS documentation.
Components of a Stored Procedure
When you create a basic stored procedure in Microsoft SQL Server, you must use the CREATE PROCEDURE
keywords. Each stored procedure must have its own unique name immediately following those keywords. The AS
keyword must be used to specify any SQL statements used within the stored procedure.
Stored procedures are very similar to high-level object-oriented programming languages (e.g., JAVA and C++)
because they accept data in the form of input parameters, as object-oriented programming languages do.
To create a stored procedure with local variables you must assign each local variable a unique name. You can name
a local variable whatever you want; however, all local variables must start with the @ symbol. They must also be
declared. To declare a variable, you must give it a unique name and assign a data type.
To enable a stored procedure to accept input parameters you must specify input parameters after the name of the
stored procedure. All input parameters must contain a name, the @ symbol, a data type and a field size.
You can also specify a return statement to return a result from a function or a print statement to display data to the
screen. Keep in mind that I have touched only the surface when it comes to stored procedures. They can be very
complex. Let me show you a simple example of a stored procedure.
Janet Creates a Stored Procedure
Janet's First SQL Statement: Create a Stored Procedure to Count the Number of Customers Who Have a Phone
Number in the Database.
The sales department plans to call every customer who has a phone number listed in the database. They want to
inform their customers about a new service plan scheduled for release next month. Jack Murphy, the manager of the
sales department, asks Janet to obtain the total number of customers who have a phone number listed in the
database. He wants to get an idea of how many customers they will need to contact.
Janet agrees and tells Jack that she will have the requested information by the close of the day.
Janet decides to use a stored procedure to display the total amount of phone numbers in the database. She can use
this stored procedure again in the future by typing a simple execute command.
She begins by typing the CREATE PROCEDURE keywords. She names the procedure CountPhoneNumbers. She
uses the AS keyword to declare local variables and specify SQL statements. After the AS keyword, she declares a
local variable (@count) as an integer.
Next, she creates an SQL statement that counts fields that are not blank within the HomePhone column. In the
SELECT statement, she sets the @count variable equal to the count (*) function. She uses a PRINT statement to
https://w w w .ed2go.com/C lassroom/P rintLesson.aspx?classroom=fTA IgP gRM ZkDIp99pM 6pBllQ lm8v G P …
9/28/12
S Q L Lev el I: Lesson 12
display the result from the stored procedure.
Janet types the following SQL statement:
CREATE PROCEDURE CountPhoneNumbers
AS
DECLARE @count INTEGER
SELECT @count = COUNT (*)
FROM Customer
WHERE HomePhone IS NOT NULL
Print @count
Processing Stored Procedures
To process the stored procedure created in Janet's first query, you must use the EXECUTE keyword.
Janet's Second SQL Statement: Create an EXECUTE Statement to Run the CountPhoneNumbers Stored
Procedure.
Janet types the EXECUTE keyword followed by the name of the stored procedure that she created in her first SQL
statement.
Janet types the following
EXECUTE statement:
EXECUTE CountPhoneNumbers
Janet's results from the stored procedure look like the image below.
Fig 12.1.
The result produces the number 13, which shows the total number of customers who currently have a phone number
listed in the database.
Janet's Third SQL Statement: Create a Stored procedure that Accepts an Input Parameter.
Janet frequently writes queries that retrieve the customers name and total number of service plans. She decides to
create a stored procedure that accepts an input parameter (CustomerID) to retrieve the customers name and total
plan count.
Janet types the CREATE PROCEDURE keywords and she names the stored procedure CustPlanCount. She
specifies an input variable (@custID) after the name of the stored procedure. The input variable contains a character
(CHAR) datatype and a field size of five. She uses the AS keyword to specify a query to retrieve the customers name
and total number of service plans.
Janet's query contains a subquery. In the outer query, she sets her input variable (@custID) equal to the Customer
ID column in the Customer table. This causes the DBMS to expect inputs equal to the customer ID s in the
Customer table.
Janet types the following SQL statement:
https://w w w .ed2go.com/C lassroom/P rintLesson.aspx?classroom=fTA IgP gRM ZkDIp99pM 6pBllQ lm8v G P …
9/28/12
S Q L Lev el I: Lesson 12
CREATE PROCEDURE CustPlanCount @custID CHAR (5)
AS
SELECT CustomerID, FirstName, LastName,
(SELECT COUNT (*) FROM Orders
WHERE Orders.CustomerID = Customer.CustomerID) AS TotalPlans
FROM Customer
WHERE Customer.CustomerID = @custID;
Janet types the EXECUTE keyword, the name of the stored procedure and a customer ID number to retrieve a
customers name and total number of service plans.
She types the following execute statement to find the total number of service plans for customer ID three.
Execute CustPlanCount 3
Fig 12.2.
The execute statement displays four columns (CustomerID, FirstName, LastName, TotalPlans for Customer ID three.
Chapter 3
Triggers
Triggers: Explanations and Definitions
One type of commonly used stored procedures is the trigger. Triggers can perform such actions as sending e-mail
and performing data validation. They are most often used to track changes made to tables, modify computed
columns, enforce referential integrity rules, and provide security.
Key Terms
CREATE TRIGGER statement. Tells the DBMS that you are creating a new trigger.
FOR. Specifies the operation that a trigger is linked to.
ON. Specifies the table that the trigger relates to.
trigger. A stored procedure that executes in response to an INSERT, UPDATE, or DELETE statement.
Upper () function. Converts all lowercase characters to uppercase characters.
The term trigger gives you some idea as to how a trigger works. When you define a trigger, you link it to a specific
operation on an individual table. When the operation in the database takes place, it triggers the execution of the
defined trigger. Once a link is created, the trigger will execute anytime that operation occurs on the table. For
example, Janet could create a trigger that deletes customers from the database when they no longer have any
service plans.
Triggers are connected to individual tables. They automatically execute before or after an INSERT, UPDATE, or
DELETE statement processes. You can define single or multiple triggers on a single table.
https://w w w .ed2go.com/C lassroom/P rintLesson.aspx?classroom=fTA IgP gRM ZkDIp99pM 6pBllQ lm8v G P …
9/28/12
S Q L Lev el I: Lesson 12
Triggers must be created on tables stored in the database. They cannot be created on views. If you remove a table
from the database, the trigger linked to that table is automatically removed too. Additionally, triggers cannot include
SELECT statements.
To create a trigger, you must specify conditions in which the trigger must be executed, and actions that the trigger
must carry out. In Microsoft SQL Server, triggers are created like stored procedures, except they must also include
the ON and FOR keywords. Look at the example below.
Janet Creates a Trigger
Janet's Fourth SQL Statement: Create a Trigger to Capitalize the States When a Customer Is Inserted or Updated.
Jack Murphy, the manager of the sales department, notices that many of the states entered into the Customer table
are not consistently entered in uppercase letters. He contacts Janet to find out if there is a way to make sure all
states are capitalized when entered.
Janet tells Jack she can combat this problem by adding a trigger to the Customer table. The trigger will
automatically capitalize the states in the State column when a new customer is entered and when existing customer
accounts are updated.
She types the CREATE TRIGGER keywords and names the trigger CapitalizeState. She uses the ON keyword to
specify the table, and the FOR keyword to specify the operation that the trigger is linked to (INSERT, UPDATE).
Finally, she types the UPDATE statement that contains the Upper () function.
Note: Janet did not include a WHERE clause in the UPDATE statement, because the condition is specified after the
FOR keyword
Janet types the following SQL statement:
CREATE TRIGGER CapitalizeState
ON Customer
FOR INSERT, UPDATE
AS
UPDATE Customer
SET State = Upper (State)
Delete a Trigger
To delete a trigger type the DROP TRIGGER keywords followed by the name of the trigger.
DROP TRIGGER TriggerName
Note: Triggers are DBMS specific. Check your database documentation.
Chapter 4
Cursors
Janet often browses through records stored in the database. She frequently checks the consistency of the data
without actually modifying it. In the past, she browsed records by opening the table that contained the data she
needed to view. Now she wants to begin using cursors to browse records.
Cursors: Explanations and Definitions
Key Terms
https://w w w .ed2go.com/C lassroom/P rintLesson.aspx?classroom=fTA IgP gRM ZkDIp99pM 6pBllQ lm8v G P …
9/28/12
S Q L Lev el I: Lesson 12
BEGIN statement. Tells the DBMS that a new procedure is beginning.
CLOSE statement. Used to free the result set by closing the cursor.
cursor. Enables you to scroll through a set of records to retrieve data.
DEALLOCATE statement. Used to release all memory associated with the cursor.
DECLARE statement. Used to define the cursor result set that will be used for all cursor operations.
END statement. Tells the DBMS that a procedure is ending.
FETCH NEXT statement. Used jointly, returns the result row immediately following the current row, and increments
the current row to the row returned.
FETCH statement. Used to specify which rows to retrieve.
OPEN CURSOR statement. Used to open a cursor.
result set. Group of records retrieved by an SQL query.
WHILE loop. Sets a condition for a repeated execution of an SQL statement or statement block.
A cursor can be used to scroll through records in any direction, one or multiple records at a time. They are commonly
used to save the results of a query to use at a later date. This is especially useful if you frequently use a result set.
Note: Typically, you should use cursors when you need to scroll through large amounts of data, usually when you
browse screens of data.
Creating a Cursor
To create a cursor, you must first declare it using the DECLARE statement. This enables you to name the cursor and
allocate space to store the cursor. Second, you must open the cursor using the OPEN CURSOR statement. Opening
the cursor retrieves and stores the requested data for scrolling. You can specify specific rows for retrieval by using a
FETCH statement. Each FETCH statement moves the cursor to the specified row in the result set before retrieving
data. After you finish data retrieval, the cursor must be closed using the CLOSE statement. When a cursor is closed,
the result set is no longer accessible.
Note: To use a closed cursor, you must reopen it.
Janet Creates a Cursor
Janet's Fifth SQL Statement: Create a Cursor to Retrieve the First and Last Name of Every Customer With a Last
Name Beginning with the Letter L.
Janet needs to create a cursor to retrieve the first and last names of every customer whose last name begins with the
letter L. She wants to scroll through the list of names to certify that they match one of her reports.
Janet uses the DECLARE statement to define a new cursor. She names the cursor CustomerCursor. She uses the
FOR keyword to specify a SELECT statement that retrieves the first and last name of every customer whose last
name begins with the letter L.
Next, Janet opens the CustomerCursor cursor. She uses FETCH and NEXT jointly to scroll through the rows. Within
a WHILE loop, she uses a global variable (@@FETCH_STATUS) to control cursor actions in the WHILE loop.
When a @@FETCH_STATUS variable returns a 0, it means the FETCH statement was successful. If it returns a -1,
the FETCH statement failed. And if it returns a -2, the row that was fetched is missing.
She uses a BEGIN statement to tell the DBMS to begin another FETCH statement. She uses the END statement to
https://w w w .ed2go.com/C lassroom/P rintLesson.aspx?classroom=fTA IgP gRM ZkDIp99pM 6pBllQ lm8v G P …
9/28/12
S Q L Lev el I: Lesson 12
tell the DBMS to end the procedure. She closes the cursor using the CLOSE statement. She doesn't plan to reuse
this cursor; therefore, she uses the DEALLOCATE statement to release all memory associated with the cursor.
Janet types the following SQL statement:
DECLARE CustomerCursor CURSOR
FOR
SELECT LastName, FirstName
FROM Customer
WHERE LastName like 'L%'
OPEN CustomerCursor
FETCH NEXT FROM CustomerCursor
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM CustomerCursor
END
CLOSE CustomerCursor
DEALLOCATE CustomerCursor
Note: Cursors are database specific. Check your DBMS documentation.
Chapter 5
Conclusion
In today's last lesson, I defined new key terms and provided additional examples using Janet Stevens.
I defined and explained the term stored procedure and introduced new key terms associated with stored procedures. I
showed you how to use the CREATE PROCEDURE statement to create a stored procedure, and how to use the
EXECUTE statement to run a stored procedure. I also showed you how to declare a local variable and how to return
results from a function using the RETURN statement.
I defined and explained the term trigger, and you learned new key terms associated with triggers. You learned how to
use the CREATE TRIGGER statement to create a trigger, and how to use the FOR and ON keywords. You also
learned how to use the Upper () function to convert lowercase characters to uppercase characters.
I defined and explained the term cursor. I also defined the term result set. You learned how to create a cursor using
the DECLARE CURSOR statement and how to declare, fetch, close, and deallocate a cursor.
In this course, you've learned the basic concepts of relational databases and SQL syntax, and how to use SQL to
manipulate data using joins, calculated fields, functions, and subqueries. You learned how to use the DELETE,
INSERT, and UPDATE statements. You learned how to create views, indexes, and constraints. You also learned how
to use advanced techniques of SQL such as transaction processing, stored procedures, triggers, and cursors.
Complete the assignment and the quiz to apply what you learned in this lesson. When you are ready, access the
completion section to take your final.
I have enjoyed teaching this class, receiving your comments, and addressing your questions and concerns. I hope
that you enjoyed Introduction to Structured Query Language and that you feel more comfortable working with
databases. You now have all the tools to work with most databases.
Note: Make sure you visit the lesson 12 discussion area to view my closing comments to you.
Good luck to you all!
https://w w w .ed2go.com/C lassroom/P rintLesson.aspx?classroom=fTA IgP gRM ZkDIp99pM 6pBllQ lm8v G P …
9/28/12
S Q L Lev el I: Lesson 12
Supplementary Material
CREATE TRIGGER
http://msdn.microsoft.com/en-us/magazine/cc164047.aspx
This site defines and explains triggers.
SQL Server Cursors
http://www.blackwasp.co.uk/SQLCursors.aspx
An overview of how to use cursors effectively in SQL Server.
Database Objects: Stored Procedures
http://www.informit.com/guides/content.aspx?
g=sqlserver&seqNum=56
This site discusses stored procedures in SQL Server.
SQL Server Stored Procedure Basics
http://www.informit.com/articles/article.aspx?
p=25288&seqNum=6&rl=1
This site explains how to create and execute stored procedures in
SQL Server.
SQL Server Stored Procedures 101
http://www.devarticles.com/c/a/SQL-Server/SQL-Server-StoredProcedures-101/1/
This site discusses and explains how to create stored procedures.
Using Triggers In MS SQL Server
http://www.devarticles.com/c/a/SQL-Server/Using-Triggers-In-MSSQL-Server/1/
This site defines and explains how triggers work in SQL Server.
FAQs
Q: Can I reuse a cursor without opening it?
A: No. You must open a closed cursor in order to use it.
Assignment
Use the Customer table from the lessons to create a trigger to capitalize the states in the state column when a
customer is inserted into the database, or when a customer's account is updated. Name the trigger
UpperCaseState.
Remember: The Customer table contains the following columns: CustomerID, FirstName, LastName,
HomePhone, Address, State, City, PostalCode.
https://w w w .ed2go.com/C lassroom/P rintLesson.aspx?classroom=fTA IgP gRM ZkDIp99pM 6pBllQ lm8v G P …
9/28/12
S Q L Lev el I: Lesson 12
Answer to Lesson 11 assignment:
BEGIN TRANSACTION
INSERT INTO ServicePlans (PlanID, PlanName,
PlanDescription, PlanPrice, DiscountedPrice)
VALUES ('M1000', 'Messaging Package',
'Two way messaging', 19.99, 16.99)
SAVE TRANSACTION Insert1
INSERT INTO Orders (CustomerID, PlanID,
OrderDate)
VALUES (20, 'M1000', '04/01/03')
IF @@ERROR <> 0 ROLLBACK TRANSACTION Insert1
COMMIT TRANSACTION
Answer to Lesson 12 assignment:
CREATE TRIGGER UpperCaseState
ON Customer
FOR INSERT, UPDATE
AS
UPDATE Customer
SET State = Upper (State)
Copyright © 1997 - 2012 Education To Go. All rights reserved. The material on this site cannot be reproduced or
redistributed unless you have obtained prior written permission from Education To Go. Education To Go and ed2go are
registered trademarks of Education To Go, a part of Cengage Learning.
https://w w w .ed2go.com/C lassroom/P rintLesson.aspx?classroom=fTA IgP gRM ZkDIp99pM 6pBllQ lm8v G P …
Download