Sunteți pe pagina 1din 12

Introduction to Stored Procedure

Copyright EME TECHNOLOGIES

Control Flow Language


Conditions
Ifelse Syntax :

If <Boolean_expression> Statements to be executed else Statements to be executed


IF EXISTS(SELECT zip FROM authors WHERE zip='9470') PRINT 'Msg print ELSE PRINT 'Msg print else'

Example:

Copyright EME TECHNOLOGIES

Transaction Control
Transaction Control Statements
COMMIT
ROLLBACK

Copyright EME TECHNOLOGIES

COMMIT
Use the COMMIT statement to end your current transaction and make permanent all changes performed in the transaction If you do not explicitly commit the transaction and the program terminates abnormally, then the last uncommitted transaction is automatically rolled back

SYNTAX: COMMIT

Copyright EME TECHNOLOGIES

ROLLBACK
Use the ROLLBACK statement to undo work done in the current transaction, or to manually undo the work done by an in-doubt distributed transaction SYNTAX: ROLLBACK

Copyright EME TECHNOLOGIES

Transaction Example
BEGIN TRAN INSERT INTO EMPLOYEE (EmpId, Fname, Lname, JobId, JobLvl) VALUES ( 'HUS42628M', 'ROGER', 'SLATE,12, 25) IF(@@ERROR <> 0) ROLLBACK TRAN ELSE BEGIN DELETE FROM Jobs WHERE jobId =13 IF(@@ERROR <> 0) BEGIN PRINT 'Record not inserted in to Employee' ROLLBACK TRAN END ELSE BEGIN PRINT 'TRANSACTION SUCCESSFUL' COMMIT TRAN END END

Copyright EME TECHNOLOGIES

What is a Stored Procedure?


A Stored procedure is a precompiled collection of Transact-SQL statements stored under a name and processed as a unit. SQL Server supplies stored procedures for managing SQL Server and displaying information about databases and users. SQL Server-supplied stored procedures are called system stored procedures.

Copyright EME TECHNOLOGIES

Stored Procedures (Continued)


A stored procedure in SQL Server is similar to a procedure in other programming languages:
Can accept input parameters and return multiple values in the form of output parameters to the calling procedure or batch Can contain programming statements that perform operations in the database, including calling other procedures Can return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure)

Copyright EME TECHNOLOGIES

Benefits of Stored Procedures


Modular programming Faster execution Reduction in network traffic Can be used as a security mechanism

Copyright EME TECHNOLOGIES

Stored Procedure Example


CREATE PROCEDURE selectAllEmployee AS select * from tb_employee

Copyright EME TECHNOLOGIES

10

Stored Procedure Example


CREATE PROCEDURE LoginUser ( @sUserName varchar(50), @sPassword varchar(50), @Sts int output ) as if exists (select sUserName,sPassword from tb_UserLogin where sUserName=@sUserName and sPassword=@sPassword) begin set @Sts=1 end else begin set @Sts=0 end RETURN @Sts
Copyright EME TECHNOLOGIES
11

Questions & Comments

Copyright EME TECHNOLOGIES

12

S-ar putea să vă placă și