Module 12: Implementing Stored Procedures
Vidya Vrat Agarwal. | MCT, MCSD
Overview
Introduction to Stored Procedures Creating, Executing, and Modifying Stored Procedures Using Parameters in Stored Procedures Executing Extended Stored Procedures
Introduction of Stored Procedures
A stored procedure is a named collection of Transact-SQL statements that is stored on the server. Stored procedures are a method of encapsulating repetitive tasks that executes efficiently. A precompiled collection of Transact-SQL statements stored under a name and processed as a unit. SQL Server-supplied stored procedures are called system stored procedures.
Named Collections of Transact-SQL Statements Encapsulate Repetitive Tasks Five Types (System, Temporary, Local, Extended and Remote) Accept Input Parameters and Return Values Return Status Value to Indicate Success or Failure
Initial Processing of Stored Procedures
Creation Creation
Entries Entries into into sysobjects sysobjects and and syscomments syscomments tables tables
Parsing Parsing
Execution Execution
(first (firsttime time or orrecompile) recompile)
Optimization Optimization
Compilation Compilation
Compiled Compiled plan plan placed placed in in procedure procedure cache cache
Advantages of Stored Procedures
Share Application Logic Shield Database Schema Details Provide Security Mechanisms Improve Performance Reduce Network Traffic
Creating Stored Procedures
Create in Current Database with the CREATE PROCEDURE Statement
Use library GO CREATE PROC[EDURE] overdue_books AS SELECT * FROM dbo.loan WHERE due_date < GETDATE() GO
Can Nest to 32 Levels Use sp_help to Display Information
EXEC overdue_books
Guidelines for Creating Stored Procedures
dbo User Should Own All Stored Procedures One Stored Procedure for One Task Create, Test, and Debug on Server Avoid sp_ Prefix in Stored Procedure Names Use Same Connection Settings for All Stored Procedures Minimize Use of Temporary Stored Procedures
Input parameters allow information to be passed into a stored procedure. To define a stored procedure that accepts input parameters, you declare one or more variables as parameters in the CREATE PROCEDURE statement. The maximum number of parameters in a stored procedure is 1024. Parameters are local to a stored procedure. The same parameter names can be used in other stored procedures.
Using Input Parameters
Create Proc Pname @myname varchar(20) = Vidya as print 'My Name is' + ' ' + @myname Exec Procedure Name [Parameter] Exec pname Vidya Exec pname Vidya Vrat Exec pname Pname
Step 1
Step 2
My Name is Vidya My Name is Vidya Vrat My Name is Vidya My Name is Vidya
create proc pst @sid as char(8) as select * from student where student_id=@sid exec pst '1111111' 1111111 Antonius Purba Male 20 Medan
Executing Stored Procedures with Input Parameters
Passing Values by Reference
EXEC EXEC addadult addadult @firstname @firstname = = 'Linda', 'Linda', @lastname @lastname = = 'LaBrie', 'LaBrie', @street @street = = 'Dogwood 'Dogwood Drive', Drive', @city @city = = 'Sacramento', 'Sacramento', @state @state = = 'CA', 'CA', @zip @zip = = '94203' '94203'
Passing Values by Position
EXEC EXEC addadult addadult 'LaBrie', 'LaBrie', 'Linda', 'Linda', null, null, 'Dogwood 'Dogwood Drive', Drive', 'Sacramento', 'Sacramento', 'CA', 'CA', '94203', '94203', null null
Updating Data
UPDATE statement NOCOUNT option
CREATE CREATE PROCEDURE PROCEDURE p_UpdateCategory p_UpdateCategory ( ( @CategoryID @CategoryID int int = = null, null, @CategoryName @CategoryName varchar(50) varchar(50) ) ) AS AS SET SET NOCOUNT NOCOUNT ON ON UPDATE UPDATE Categories Categories SET SET Category Category = = @CategoryName @CategoryName WHERE WHERE CategoryID CategoryID = = @CategoryID @CategoryID
Inserting Data
INSERT Statement
CREATE CREATE PROCEDURE PROCEDURE p_InsertCustomer p_InsertCustomer ( ( @FName @FName varchar(50), varchar(50), @LName @LName varchar(50) varchar(50) ) ) AS AS SET SET NOCOUNT NOCOUNT ON ON INSERT INSERT INTO INTO Customers Customers (FirstName, (FirstName, LastName) LastName) VALUES VALUES (@FName, (@FName, @LName) @LName)
Deleting Data
DELETE Statement
CREATE CREATE PROCEDURE PROCEDURE p_DeleteCategory p_DeleteCategory ( ( @CategoryID @CategoryID int int = = null null ) ) AS AS SET SET NOCOUNT NOCOUNT ON ON DELETE DELETE FROM FROM Categories Categories WHERE WHERE CategoryID CategoryID = = @CategoryID @CategoryID
Returning Values with Output Parameters
CREATE CREATE PROCEDURE PROCEDURE mathtutor mathtutor @m1 @m1 smallint, smallint, @m2 @m2 smallint, smallint, @result @result smallint smallint OUTPUT OUTPUT AS AS SET SET @result @result = = @m1 @m1 * * @m2 @m2 DECLARE DECLARE @answer @answer smallint smallint EXECUTE EXECUTE mathtutor mathtutor 5, 5, 6, 6, @answer @answer OUTPUT OUTPUT SELECT SELECT 'The 'The result result is: is: ' ', , @answer @answer
Creating CreatingStored Stored Procedure Procedure
Executing ExecutingStored Stored Procedure Procedure
Results Resultsof ofStored Stored Procedure Procedure
The The result result is: is: 30 30
OUTPUT Parameter
Stored procedures can return information to the calling stored procedure or client with output parameters (variables designated with the OUTPUT keyword). By using output parameters, any changes to the parameter that result from the execution of the stored procedure can be retained, even after the stored procedure completes execution. To use an output parameter, the OUTPUT keyword must be specified in both the CREATE PROCEDURE and EXECUTE statements. If the keyword OUTPUT is omitted when the stored procedure is executed, the stored procedure still executes, but it does not return a value. i.e. Shows NULL .
Executing Extended Stored Procedures
Increase SQL Server Functionality Are Programmed Using Open Data Services API Can Include C and C++ Features Can Be Added to the master Database Only
EXEC master..xp_cmdshell 'dir c:\mssql7'
Return Statement
The RETURN statement exits from a query or stored procedure unconditionally. It also can return an integer status value (return code). A return value of 0 indicates success; 1-99 indicates error
Return statement
create proc ps @age int as if (@age > 28) return (1) select * from student where age >=@age return(0) declare @status int exec @status= ps 20 select @status
Check Your Understanding.
Q.1 What is Stored Procedure.?
Q.2. How many types of stored procedures are available with SQL server. ?
Q.3. You should use sp_ Prefix in Stored Procedure Names.?
1. 2.
Yes No
Q.4. Return Value, Indicates Success or Failure.? True False
1. 2.
Q.5. The maximum number of parameters in a stored
procedure is _____________ .
Q.6. What will be the output of the following : EXEC master..xp_cmdshell 'dir c:\mssql7
Q.7. Name the five stored procedures available with SQL Server.
Q.8. What are the Mistakes in the given Create Proc command. cREATE pROC Pname myname varchar(20) = PIDel as print 'My Name is' + ' ' + @myname
Q.9. The same parameter names can be used in other stored procedures.
True False
1. 2.
Q.10. If the keyword OUTPUT is omitted when the stored
procedure is executed, the stored procedure still executes, but it does not return a value.
1. 2.
True False
Q.11. A junior SQL Server programmer asks you for help. She
executed a SQL statement on the server from her computer. Before she could verify that it executed properly, she lost network connectivity. From your computer, you access the server and use the @@error system function. It returns a value of 0. What does that indicate about the last statement executed on the server? It stopped executing due to the loss of connectivity. It logged an error number 0. It logged an error with a severity level of 0. It is executed successfully.
1. 2. 3. 4.
Q.12. You are the system administrator of a production database server. You want to create a stored procedure to automate certain administrative tasks on the Finance database. You do not want the stored procedure to be used in other databases. What type of stored procedure should you use?
1. 2. 3. 4.
System Local Global temporary Extended.
Review
Introduction to Stored Procedures Creating, Executing, and Modifying Stored Procedures Using Parameters in Stored Procedures Executing Extended Stored Procedures
It is not enough to aim you must Hit .
Thank You.