sql server ___________session_18(stored procedures)

25
STORED PROCEDURES

Upload: ehtisham-ali

Post on 14-Apr-2017

304 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Sql server  ___________session_18(stored procedures)

STORED PROCEDURES

Page 2: Sql server  ___________session_18(stored procedures)

CONTENTS Introduction to stored procedures Types of Stored Procedure

User defined stored procedures Extended stored procedures System stored procedures

Page 3: Sql server  ___________session_18(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.

Page 4: Sql server  ___________session_18(stored procedures)

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

Page 5: Sql server  ___________session_18(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

Page 6: Sql server  ___________session_18(stored procedures)

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’

Page 7: Sql server  ___________session_18(stored procedures)

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’

Page 8: Sql server  ___________session_18(stored procedures)

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’

Page 9: Sql server  ___________session_18(stored procedures)

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’

Page 10: Sql server  ___________session_18(stored procedures)

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.

Page 11: Sql server  ___________session_18(stored procedures)

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

Page 12: Sql server  ___________session_18(stored procedures)

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'

Page 13: Sql server  ___________session_18(stored procedures)

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

Page 14: Sql server  ___________session_18(stored procedures)

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'

Page 15: Sql server  ___________session_18(stored procedures)

Using Wildcard Characters:

Create procedure wild_cards @name varchar(20) as Select * from employee where emp_name like @name

execute wild_cards 'D%'

Page 16: Sql server  ___________session_18(stored procedures)

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.

Page 17: Sql server  ___________session_18(stored procedures)

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)

Page 18: Sql server  ___________session_18(stored procedures)

exec usp_adduser ‘dnelson’, ‘dean2003′, ‘Dean’, ‘Nelson’, ’200 Berkeley Street’, ‘ ‘, ‘Boston’, ‘MA’, ’02116′, ‘[email protected]

Page 19: Sql server  ___________session_18(stored procedures)

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

Page 20: Sql server  ___________session_18(stored procedures)

CREATE PROCEDURE usp_finduser @usr_id int AS SELECT * FROM USERLIST

WHERE usr_id=@usr_id

Execute Statement: exec usp_finduser ’1′

Page 21: Sql server  ___________session_18(stored procedures)

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

Page 22: Sql server  ___________session_18(stored procedures)

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.

Page 23: Sql server  ___________session_18(stored procedures)

ERROR Function

Error_line() Error_number() Error_message() Error_procedure() Error_severity() Error_state()

Page 24: Sql server  ___________session_18(stored procedures)

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

Page 25: Sql server  ___________session_18(stored procedures)

Sp_addmessage stored procedure

Execute sp_addmessage @msgnum=50001, @severity=10,

@msgtext=‘This is a customized error’,

@lang=‘us_english’

Raiserror(50001,10,1)