Advanced SQL- LAB 3
Subqueries,
DCL and TCL
Statements
Variables,
Selection, and
Iteration
Stored
Procedures
Tables and
Functions
Error
Handling
Using DDL Statements The Knowledge Academy
Advanced SQL – LAB 3
1. Overview.............................................................................................................................................................. 2
2. The Lab Contents ................................................................................................................................................. 2
3. Stored Procedures ............................................................................................................................................... 3
3.1 Creating a Stored Procedure .............................................................................................................................. 3
3.1.1 Using the Object Explorer ........................................................................................................................... 3
3.1.2 Using the Query Window ............................................................................................................................ 4
3.2 Executing Stored Procedures ............................................................................................................................. 5
3.2.1 Using the Object Explorer ........................................................................................................................... 5
3.2.2 Using the Query Window ............................................................................................................................ 6
3.2.3 Calling from another Application ................................................................................................................ 7
3.3 Parameters ......................................................................................................................................................... 7
3.3.1 Creating Parameter based Procedure.................................................................................................. 7
3.3.2 Procedure with Multiple Parameters .................................................................................................. 8
3.3.3 Providing DEFAULT Values for Parameters .......................................................................................... 9
3.4 Returning Values ..............................................................................................................................................10
3.4.1 Using Output to Return Values .................................................................................................................10
3.4.2 Using Return to Return Values..................................................................................................................10
4. System Stored Procedures ................................................................................................................................12
4.1 sp_help System Stored.....................................................................................................................................12
4.2 sp_tables System Stored Procedure ................................................................................................................12
4.3 sp_helptext System Stored Procedure ............................................................................................................13
4.4 sp_depends System Stored Procedure ............................................................................................................13
Page | 1
Using DDL Statements The Knowledge Academy
1. Overview
The Lab 3 of Advanced SQL course deals with Stored Procedures of different types,
Parameters, and Return values.
2. The Lab Contents
Tasks
Stored Procedures
Passing Parameters
Returning Values
System Stored Procedures
Cursors
Triggers
Page | 2
Using DDL Statements The Knowledge Academy
3. Stored Procedures
Stored Procedures contain valid SQL Server statement which are stored as a group
under a name. These procedures can be called whenever required. Stored Procedures
are present under the PROGRAMIBILTY node in the current database.
3.1 Creating a Stored Procedure
A stored procedure can be created in two ways – using the Object Explorer or using
the Query Window.
3.1.1 Using the Object Explorer
To create a Stored Procedure using the Object Explorer follow the steps
Locate the Database CustomerOrders
Expand it to show the nodes under it
Locate the Programmability node and expand it
The first node under Programmability is the Stored Procedure node as shown
Figure 1. The Stored Procedure Node
Right Click the Stored Procedures node to bring up the context menu as shown
Figure 2. Creating a New Stored Procedure
Click the Stored Procedure …. option as shown above
Page | 3
Using DDL Statements The Knowledge Academy
This brings up a template code where the values such as Procedure Name and
Parameters can be substituted as required
Replace the code you want to execute by using this procedure
Click EXECUTE button from the Standard Toolbar
Click Refresh from the Stored Procedures Context Menu
You can find the procedure you created
3.1.2 Using the Query Window
It is much easier to create a stored procedure from the Query Window. Follow the steps
to create the procedure CustRecs that displays all the records from the Customer table
who reside in a specific city.
Click New Query option from the Standard Toolbar
Type the following code in the Query Window
Create Procedure AllCust
as
Begin
Select * from Customer order by Country, City
End
Click Execute from the Standard Toolbar
Type the following code in the Query Window
Exec AllCust
Click Execute from the Standard Toolbar
Figure 3. Executing Stored Procedure
Page | 4
Using DDL Statements The Knowledge Academy
3.2 Executing Stored Procedures
There are different ways of executing a stored procedure. They are using the object
explorer, using the query window, or calling from another application.
3.2.1 Using the Object Explorer
Locate the Database CustomerOrders
Expand it to show the nodes under it
Locate the Programmability node and expand it
Expand the Stored Procedure node under Programmability
Locate the procedure AllCust
Right click the procedure name and bring up the Context Menu
Click EXECUTE STORED PROCEDURE … as shown below
Figure 4. Using Object Explorer
This brings up the following screen
Page | 5
Using DDL Statements The Knowledge Academy
Figure 5. The Execute Procedure Window
Click OK
You see the following result
Figure 6.Procedure Output
3.2.2 Using the Query Window
Select the database CustomerOrders
Click New Query option from the Standard Toolbar
Type the following code in the Query Window
Page | 6
Using DDL Statements The Knowledge Academy
Exec AllCust
Click Execute from the Standard Toolbar
You get the output as follows
Figure 7. Using EXEC from the Query Window
3.2.3 Calling from another Application
The procedures created in SQL Server can also be used by applications that use the SQL
SERVER as their back-end database. As an example, VB.Net calls the stored procedure
using the CALL statement as follows
CALL AllCust
This code can be executed from within the application and not from anywhere in the SQL
Server database.
3.3 Parameters
Parameters are extra information that are provided to the procedures for completing its
execution. A procedure may or may not have any parameters. The following example list
all customers living in Sydney.
3.3.1 Creating Parameter based Procedure
Create Procedure CustRecs
@City varchar (30)
as
Begin
Select * from Customers Where City = @City
End
Page | 7
Using DDL Statements The Knowledge Academy
Click Execute from the Standard Toolbar
Type the following code in the Query Window
Exec CustRecs “Melbourne”
Click Execute from the Standard Toolbar
You get the output as follows
Figure 8. Parameter based Procedure
3.3.2 Procedure with Multiple Parameters
Let’s create a procedure to get the name of all customers who live in Australia and in the
city Melbourne.
Type the following code in the Query Window
Create Procedure MultiParam
@City varchar (30),
@Country varchar (30)
AS
Begin
Select CustomerName, City, Country from Customer where City = @City
and Country = @Country
End
Click Execute from the Standard Toolbar
Type the following code in the Query Window
Exec CustRecs “Melbourne”, “Australia”
Click Execute from the Standard Toolbar
You get the output as follows
Page | 8
Using DDL Statements The Knowledge Academy
Figure 9. Using Multiple Parameters
3.3.3 Providing DEFAULT Values for Parameters
Type the following code in the Query Window
ALTER Procedure MultiParam
@City varchar (30) ='Sydney',
@Country varchar (30) ='Australia'
AS
Begin
Select CustomerName, City, Country from Customer where City = @City and
Country = @Country
End
Click Execute from the Standard Toolbar
Type the following code in the Query Window
Exec MultiParam
Click Execute from the Standard Toolbar
You get the output as follows
Figure 10. Using Default Values for Parameters
Page | 9
Using DDL Statements The Knowledge Academy
3.4 Returning Values
3.4.1 Using Output to Return Values
Procedures can not only accept values using parameters they can also return the values
back using a special type of parameters called the OUTPUT parameters.
In the Query Window type the following code
Create Procedure CustZip
@CustomerName varchar (30),
@PostalCode varchar (10) = NULL OUTPUT
As
Begin
Select @PostalCode=PostalCode from Customer
Where CustomerName=@CustomerName
Print 'Postal Code = '+@PostalCode
End
Click the Execute button from the Standard Toolbar
In the Query Window type the following code
Exec CustZip ‘John Carter’
Click the Execute button from the Standard Toolbar
You get the following Output
Figure 11. Using Output to Return Values
3.4.2 Using Return to Return Values
A better way to return values from a procedure is by using the RETURN keyword. The
following example illustrates the use of the RETURN keyword
Return the Postal Code of a Customer whose name is passed to an anonymous
procedure.
Page | 10
Using DDL Statements The Knowledge Academy
In the Query Window type the following code
Create Procedure CustZip
@CustomerName varchar (30),
@PostalCode varchar (10) = NULL OUTPUT
As
Begin
Select @PostalCode=PostalCode from Customer
Where CustomerName=@CustomerName
Return @PostalCode
End
Click the Execute option from the Standard Toolbar to get the following output
Figure 12. Using the RETURN Keyword
In the Query Window now type the following code
Declare
@zip varchar(10)
begin
EXEC @zip=Custzip 'Katherine'
Print @zip
End
Click the Execute option from the Standard Toolbar to get the following output
Page | 11
Using DDL Statements The Knowledge Academy
Figure 13. Using the Returned Value
4. System Stored Procedures
This part of the Lab Session deals with System Defined Stored Procedures. These
Procedures are used to either maintain the system or get knowledge about the database
and the objects in it.
4.1 sp_help System Stored
The procedure displays information about a specific database object.
Type the following in the Query Window
sp_help MultiParam
Click the Execute option from the Standard Toolbar
You get the following output
Figure 14. sp_help System Stored Procedure
4.2 sp_tables System Stored Procedure
The stored procedure returns information about a table
Type the following in the Query Window
sp_tables Orders
Page | 12
Using DDL Statements The Knowledge Academy
Click the Execute option from the Standard Toolbar
You get the following output
Figure 15.sp_tables System Stored Procedure
4.3 sp_helptext System Stored Procedure
This stored procedure returns the query details of a procedure
Type the following in the Query Window
sp_helptext CustRecs
Click the Execute option from the Standard Toolbar
You get the following output
Figure 16. sp_helptext System Stored Procedure
4.4 sp_depends System Stored Procedure
The system stored procedure sp_depends shows the columns and tables on which a
procedure depends
This stored procedure returns the query details of a procedure
Type the following in the Query Window
Sp_depends MultiParam
Click the Execute option from the Standard Toolbar
You get the following output
Page | 13
Using DDL Statements The Knowledge Academy
Figure 17. The sp_depends System Stored Procedure
5. Cursors
Cursors in SQL Server are used as a means to retrieve multiple rows one by one. There
are various types of cursors such as Forward Only, and Scroll Cursors.
5.1 Forward Only Cursors
Forward only cursors have the ability of moving from the beginning towards the end of
the result set. They cannot jump to a random position or even move backward.
Type the following in the Query Window
Declare @CustName varchar (30)
Declare @City varchar (30)
Declare CustCur Cursor
for Select CustomerName, City from Customer
Begin
Open CustCur
Fetch CustCur into @CustName, @City
Print 'Customer Name:'+@CustName
Print ‘City:'+@City
Close CustCur
End
Deallocate CustCur
Click the Execute option from the Standard Toolbar
You get the following output
Page | 14
Using DDL Statements The Knowledge Academy
Figure 18. Using a Forward Only Cursor
5.2 Another Example of Cursors
Let’s retrieve all records from the Customer table using a Forward Only Cursor.
Type the following in the Query Window
Declare @CustName varchar(30)
Declare @City varchar(30)
Declare CustCur Cursor
for
Select CustomerName, City from Customer
Begin
Open CustCur
While @@FETCH_STATUS=0
Begin
Fetch CustCur into @CustName, @City
Print 'Customer Name:'+@CustName
Print ‘City:'+@City
End
Close CustCur
End
Deallocate CustCur
Click the Execute option from the Standard Toolbar
You get the following output
Page | 15
Using DDL Statements The Knowledge Academy
Figure 19. Example Forward Only Cursor
5.3 Scroll Cursor
A Scroll Cursor is a cursor that is capable of moving forward as well as backward. IT can
move from the current position to another relative position also.
Type the following in the Query Window
Declare scroll_cursor cursor
scroll for select * from customer
Begin
Open scroll_cursor
While @@Fetch_Status=0
Begin
Fetch NEXT from scroll_cursor
End
Close scroll_cursor
End
Deallocate scroll_cursor
Click the Execute option from the Standard Toolbar
You get the following output
Page | 16
Using DDL Statements The Knowledge Academy
Figure 20. Using Scroll Cursors
6. Triggers
Triggers in SQL Server are procedures which execute whenever an action takes place.
They are generally classified into simple triggers and INSTEADOF triggers
6.1 Simple Triggers
Create a Trigger to disallow any DDL operations on the CustomerOrders database.
Type the following in the Query Window
USE [CustomerOrders]
GO
Create Trigger [Trig] On Database
For Create_Table, ALter_Table, Drop_Table
As
Print'DDL Operations Not Allowed On This Database'
Rollback Tran
Page | 17
Using DDL Statements The Knowledge Academy
Click the Execute option from the Standard Toolbar
Next, try creating, deleting, or altering a table
You get the following output
Figure 21. Database Triggers
6.2 DML Triggers
Create a Trigger to disallow DML operations
Type the following in the Query Window
Use CustomerOrders
Go
Create Trigger DMLStmt
on FavCustomer
For Insert, Delete
As
Print 'Insert, Delete Not Allowed'
Rollback Tran
Click the Execute option from the Standard Toolbar
Next, try inserting, deleting or updating a table
You get the following output
Figure 22. DML Triggers
Page | 18
Using DDL Statements The Knowledge Academy
6.3 INSTEADOF Triggers
INSTEADOF Triggers are those triggers whose statement will be executed INSTEAD OF
the DML Statement to which the trigger is linked. If an INSTEADOF Trigger exists for an
INSERT in table Customer, the statements in the trigger will execute instead of the
INSERT statement.
Synchronize the two tables Customer and CustomerBak to contain the latest INSERTED
records
Type the following in the Query Window
Use CustomerOrders
Go
Create Trigger InstTrig
On Customer
INSTEAD of INSERT
AS
Begin
INSERT INTO CUSTOMER
Select I.CustomerId, I.CustomerName, I.City,
I.Country, I.PostalCode From Inserted I
INSERT INTO CustomerBackup
Select I.CustomerId, I.CustomerName, I.City,
I.Country, I.PostalCode From Inserted I
END
Select * from CustomerBackup
Click the Execute option from the Standard Toolbar
Next, try inserting, deleting or updating a table
You get the following output
Page | 19
Using DDL Statements The Knowledge Academy
Figure 23. INSTEADOF Triggers
6.4 After Insert Triggers
An After Insert Trigger can be used to display success or failure messages or even
display the records after insertion. Display a message “Record Successfully Inserted”
after inserting a record into the customer table
Type the following in the Query Window
Create Trigger AftInst
on Customer
After Insert
As
Begin
Print' Record Successfully Inserted'
End
Click the Execute option from the Standard Toolbar
From the Query Window issue the statement
Insert into customer values (5611,'Ricky Ponting','Perth','Australia','WA6105')
Click the Execute option from the Standard Toolbar to see the output
Figure 24. After Insert Triggers
===================== End of Lab Session 3 =======================
Page | 20