Date post: | 14-Apr-2017 |
Category: |
Education |
Upload: | ehtisham-ali |
View: | 302 times |
Download: | 0 times |
STORED PROCEDURES
CONTENTS Introduction to stored procedures Types of Stored Procedure
User defined stored procedures Extended stored procedures System stored procedures
INTRODUCTION TO STORED PROCEDURES
A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.
In addition to running the same SQL code over and over again you also have the ability to pass parameters to the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the parameter values that were passed.
User Defined: User defined stored procedures are also
known as custom stored procedures.These procedures are used for reusing Transact-SQL statements for performing repetitive task.
Extended Stored procedures: Extended stored procedures help SQL in
interecting with operating system.These are carried out in DLL(Dynamic Link Library).It calls at the runtime.
Types Of Stored Procedures
System Stored Procedure
System stored procedure are commonly used for interacting with system tables.
They are prefixed with ‘sp_’ Catalog Stored Procedure Database Stored Procedure Database Engine Stored Procedure Security Stored Procedure Full-text Stored Procedure
Catalog stored procedure:
sp_tables
exec sp_tables ‘%’,’dbo’,’students’
sp_stored_procedures
exec sp_stored_procedure ‘students’
sp_pkeys
exec sp_pkeys ‘student_info’
Database Engine Stored Procedures
Sp_who: sp_who[[@login_name=] ‘login’ execute sp_who
Sp_help: sp_help [ [@objectname= ] ‘name’] execute sp_help ‘table_name’
Sp_recompile: sp_recompile [@objectnm =] ‘storedproc_name’ sp_recompile ‘customer’
Security Stored procedures:
sp_addlogin
sp_addlogin [ @loginame = ] 'login' [ , [ @passwd = ] 'password' ] [ , [ @defdb = ] 'database' ] [ , [ @deflanguage = ] 'language' ]
execute sp_addlogin ‘abc’,’123’,’1106E1’exec sp_adduser ‘abc’sp_droplogin
execute sp_droplogin ‘login_name’exec sp_droplogin ‘abc’
Full-Text Stored procedures:
Sp_fulltext_catalog
exec sp_fulltext_catalog ‘ft_search’, ‘create’
• Sp_fulltext_table
exec sp_fulltext_table ‘customer’,’create’,’ft_search’,’pk_CustId’
• Sp_help_fulltext_tables
exec sp_help_fulltext_tables ‘ft_search’
USER DEFINED STORED PROCEDURE
Stored procedures are modules or routines that encapsulate code for reuse. A stored procedure can take input parameters, return tabular or scalar results and messages to the client, invoke data definition language (DDL) and data manipulation language (DML) statements, and return output parameters.
Create Stored Procedure
CREATE PROCEDURE GetStudentIdentification AS BEGIN SELECT std_name, father_name,contact_number FROM students_information END GO
Execute Stored Proceedure
exec GetStudentIdentification
The code inside the stored procedure can be something as simple as:
SELECT * FROM USERLIST
Example: Assume we have a table inventory This information is updated in real-time and
warehouse managers are constantly checking the levels of products stored at their warehouse and available for shipment. In the past, each manager would run queries similar to the following:
SELECT Product, Quantity FROM InventoryWHERE Warehouse = 'FL'
We can simplify this process through the use of a stored procedure
CREATE PROCEDURE sp_GetInventory@location varchar(10)ASSELECT Product, QuantityFROM InventoryWHERE Warehouse = @location
Our Florida warehouse manager can then access inventory levels by issuing the command
EXECUTE sp_GetInventory 'FL‘
The New York warehouse manager can use the same stored procedure to access that area's inventory.
EXECUTE sp_GetInventory 'NY'
Using Wildcard Characters:
Create procedure wild_cards @name varchar(20) as Select * from employee where emp_name like @name
execute wild_cards 'D%'
Input Variables There are many reasons for wanting to pass data to a
stored procedure, especially if your stored procedure is being called by a dynamic web page or other application.
You may want to use a SELECT statement to pull information into the application for dynamic display. In this case, you would pass selection criteria to the stored procedure (for use in a WHERE clause).
If you are inserting new records, you will need to get the data from somewhere. Updating existing records also involves simply getting the data. In both INSERT and UPDATE statements, it is necessary to pass data to the stored procedure. For INSERT, UPDATE, and SELECT statements (to name a few), you can pass the data to your stored procedure using variables.
CREATE PROCEDURE usp_adduser @login varchar(20),
@pswd varchar(20),@f_name varchar(25),@l_name varchar(35),@address_1 varchar(30),@address_2 varchar(30),@city varchar(30),@state char(2),@zipcode char(10),@email varchar(50)
AS INSERT INTO USERLIST (login, pswd, f_name, l_name,
address_1, address_2, city, state, zipcode, email) VALUES (@login, @pswd, @f_name, @l_name, @address_1,
@address_2, @city, @state, @zipcode, @email)
exec usp_adduser ‘dnelson’, ‘dean2003′, ‘Dean’, ‘Nelson’, ’200 Berkeley Street’, ‘ ‘, ‘Boston’, ‘MA’, ’02116′, ‘[email protected]’
CREATE PROCEDURE usp_updateuser @usr_id int,@login varchar(20),@pswd
varchar(20),@f_name varchar(25),@l_name varchar(35),@address_1 varchar(30),@address_2 varchar(30),@city varchar(30),@state char(2),@zipcode char(10),@email varchar(50)
AS UPDATE USERLIST SET login=@login, pswd=@pswd,
f_name=@f_name, l_name=@l_name,address_1=@address_1,address_2=@address_2,city=@city, state=@state,zipcode=@zipcode, email=@email
WHERE usr_id=@usr_id
CREATE PROCEDURE usp_finduser @usr_id int AS SELECT * FROM USERLIST
WHERE usr_id=@usr_id
Execute Statement: exec usp_finduser ’1′
If – else statement create procedure insert_details@emp_id bigint,@emp_nm varchar(50),@emp_age bigint,@emp_sal bigint,@mgr_id bigintas if @emp_id is nullbegin print 'hello' return end else begin insert into emp_copy
values(@emp_id,@emp_nm,@emp_age,@emp_sal,@mgr_id) end
TRY…….CATCH Construct Each try catch construct must be inside a stored
procedure. A TRY block must be immediately followed by a CATCH
block. To handle an error that occurs within a given CATCH
block, write a TRY…CATCH block within the specified CATCH block.
Errors that have the 10 or below severity level are not handled by try…catch blocks. These errors are considered as warning or informational messages.
Errors that have severity of 20 or higher are not handled by try…catch blocks. Database engine close the connection will not be handled by the try..catch block.
ERROR Function
Error_line() Error_number() Error_message() Error_procedure() Error_severity() Error_state()
EXAMPLE
Create procedure delete_employee@empid bigintAsSet @empid=‘E001’Delete from employee where emp_id=@empid
Begin tryExecute delete_employeeEnd tryBegin catchSelect error_procedure() as ErrorProcedureEnd catch
Sp_addmessage stored procedure
Execute sp_addmessage @msgnum=50001, @severity=10,
@msgtext=‘This is a customized error’,
@lang=‘us_english’
Raiserror(50001,10,1)