Published on

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Faculty Notes : if Defines conditional execution. … else Defines alternate execution when the if condition is false. case Defines conditional expressions using when…then statements instead of if…else. begin Beginning of a statement block. … end End of a statement block. while Repeat performance of statements while condition is true. break Exit from the end of the next outermost while loop. … continue Restart while loop. declare Declare local variables. goto label Go to label:, a position in a statement block. return Exit unconditionally. waitfor Set delay for command execution. print Print a user-defined message or local variable on user’s screen. raiserror Print a user-defined message or local variable on user’s screen and set a system flag in the global variable @@ error . /* comment */ or -- comment Insert a comment anywhere in a Transact-SQL statement.
  • Faculty Notes: Example: if exists(select zip from authors where zip='9470') print 'Msg print' else print 'Msg print else'
  • Faculty Notes : Example: select CASE convert(int, (RAND() * 3)) when 0 then "A" when 1 then "B" else "E" end
  • Faculty Notes : The begin and end keywords create a block for a series of statements enclosed in it. This is treated as one unit by control of flow constructs. Enclosed statements in begin and end are called a statement block . The syntax of begin...end is: begin statement block end
  • Faculty Notes: A typical transaction is a catalog merchandise order phoned in by a customer and entered into a computer by a customer representative. The order transaction involves checking an inventory database, confirming that the item is available, placing the order and confirming that the order has been placed and noting the expected time of shipment. If we view this as a single transaction, then all of the steps must be completed before the transaction is successful and the database is actually changed to reflect the new order. If something happens before the transaction is successfully completed, any changes to the database must be documented so that they can be undone. SQL Server transactions are often described as having the ACID properties or "passing the ACID test," where ACID is an acronym for atomic, consistent, isolated, and durable. Transactional adherence to the ACID tenets is commonplace in modern RDBMS and is a prerequisite for ensuring the safety and reliability of data.
  • Faculty Notes: Review points on slide
  • Faculty Notes: Review points on slide
  • Faculty Notes: Review points on slide
  • Faculty Notes: We can begin a Transaction explicitly using keyword BEGIN TRANS and End Trans and add the statements to be executed. When this transition is executed if any of the statements fail the whole transaction will be rolled back In the Example two statements are executed one after another in a transaction The insert statement is executed and one row is inserted (But not yet committed its still in the Transaction) Assume the Delete Statement fails, as Job id 13 is in use in another child table. The @@ERROR variable checks if there’s any error for the transaction and if found rolls back the whole transaction as a whole i.e. It does not insert the record in the employee table
  • Faculty Notes: These variables are provided by SQL Server. Explanation of each has been described above.
  • Faculty Notes: Review points on slide
  • Faculty Notes: Review points on slide
  • Faculty Notes: Modular programming You can create the procedure once, store it in the database, and call it any number of times in your program. Stored procedures can be created by a person who specializes in database programming, and they can be modified independently of the program source code. Faster Execution If the operation requires a large amount of Transact-SQL code or is performed repetitively, stored procedures can be faster than batches of Transact-SQL code. They are parsed and optimized when they are created, and an in-memory version of the procedure can be used after the procedure is executed the first time. Transact-SQL statements repeatedly sent from the client each time they run, are compiled and optimized every time they are executed by SQL Server. Network traffic An operation requiring hundreds of lines of Transact-SQL code can be performed through a single statement that executes the code in a procedure, rather than by sending hundreds of lines of code over the network. Security Mechanism Users can be granted permission to execute a stored procedure even if they do not have permission to execute the procedure's statements directly.
  • Faculty Notes: procedure_name Is the name of the new stored procedure. ; number Is an optional integer used to group procedures of the same name so they can be dropped together with a single DROP PROCEDURE statement. For example, the procedures used with an application called orders may be named orderproc ;1, orderproc ;2, and so on. @ parameter Is a parameter in the procedure. One or more parameters can be declared in a CREATE PROCEDURE statement. The value of each declared parameter must be supplied by the user when the procedure is executed (unless a default for the parameter is defined). Specify a parameter name using an at sign (@) as the first character. data_type Is the parameter data type. All data types, including text, ntext and image , can be used as a parameter for a stored procedure. Note   There is no limit on the maximum number of output parameters that can be of cursor data type. VARYING Specifies the result set supported as an output parameter (constructed dynamically by the stored procedure and whose contents can vary). Default Is a default value for the parameter. If a default is defined, the procedure can be executed without specifying a value for that parameter. n Is a placeholder indicating that a maximum of 2,100 parameters can be specified. {RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION} RECOMPILE indicates that SQL Server does not cache a plan for this procedure and the procedure is recompiled at run time. ENCRYPTION indicates that SQL Server encrypts the syscomments table entry containing the text of the CREATE PROCEDURE statement. FOR REPLICATION Specifies that stored procedures created for replication cannot be executed on the Subscriber. A stored procedure created with the FOR REPLICATION option is used as a stored procedure filter and only executed during replication. This option cannot be used with the WITH RECOMPILE option. AS Specifies the actions the procedure is to take. sql_statement Is any number and type of Transact-SQL statements to be included in the procedure. Some limitations apply. n Is a placeholder that indicates multiple Transact-SQL statements may be included in this procedure.
  • Faculty Notes: The above example creates a stored procedure spAuthorDetail it accepts one parameter @AuthId of int data type when the sp is to be executed the user has to pass value to the stored procedure as shown below execute spAuthorDetail 1456 The values passed to the stored procedure are further passed to the select query. Based on the parameter passed the select statement is executed .
  • Facutly notes: We can also use function to insert data into a table Insert into mytab values (dbo.addition(2,2))
  • Faculty Notes: Review the key points on the slide. The key points should be used to summarize the content covered throughout this presentation.
  • Module04

    1. 1. Introduction to Stored Procedure & Functions Module 4
    2. 2. <ul><li>Branching Controls </li></ul><ul><li>Transactions </li></ul><ul><li>Stored Procedures </li></ul><ul><ul><li>Benefits </li></ul></ul><ul><ul><li>Rules </li></ul></ul><ul><ul><li>Types of Stored Procedure </li></ul></ul><ul><ul><li>Types of Parameter </li></ul></ul><ul><ul><li>Executing Stored Procedure </li></ul></ul><ul><ul><li>Working with stored procedure </li></ul></ul><ul><ul><li>Delete Stored Procedure </li></ul></ul><ul><li>User Defined Functions </li></ul>Learning Objectives
    3. 3. <ul><li>At the end of this section, you should be able to work with: </li></ul><ul><li>Branching Controls </li></ul><ul><li>Transactions Blocks </li></ul><ul><li>Stored Procedures </li></ul><ul><li>Functions </li></ul>Module 4 : Agenda
    4. 4. <ul><li>Conditions </li></ul><ul><ul><li>If Conditions </li></ul></ul><ul><ul><li>Case Expression </li></ul></ul><ul><li>Declare </li></ul><ul><li>Begin…End </li></ul>Control Flow Language
    5. 5. Control Flow Language <ul><li>Conditions </li></ul><ul><ul><li>If…else </li></ul></ul><ul><ul><li>Syntax : </li></ul></ul><ul><li>Example: </li></ul><ul><ul><ul><li>If <Boolean_expression> </li></ul></ul></ul><ul><ul><ul><li>Statements to be executed </li></ul></ul></ul><ul><ul><ul><li>else </li></ul></ul></ul><ul><ul><ul><li>Statements to be executed </li></ul></ul></ul><ul><ul><li>IF EXISTS ( SELECT zip </li></ul></ul><ul><ul><li> FROM authors </li></ul></ul><ul><ul><li> WHERE zip='9470') </li></ul></ul><ul><ul><ul><li>PRINT 'Msg print‘ </li></ul></ul></ul><ul><ul><li>ELSE </li></ul></ul><ul><ul><ul><li>PRINT 'Msg print else' </li></ul></ul></ul>
    6. 6. <ul><li>Conditions </li></ul><ul><ul><li>Case Expression </li></ul></ul><ul><ul><li>Syntax : </li></ul></ul><ul><ul><li>Example: </li></ul></ul>Control Flow Language <ul><ul><ul><li>case <expression> </li></ul></ul></ul><ul><ul><ul><li>when <value1> then <result1> </li></ul></ul></ul><ul><ul><ul><li>when <valuen> then <resultn> </li></ul></ul></ul><ul><ul><ul><li>else <result> </li></ul></ul></ul><ul><ul><ul><li>End </li></ul></ul></ul>SELECT CASE convert(int, (RAND() * 3)) WHEN 0 THEN ‘ A ’ WHEN 1 THEN ‘ B ’ ELSE ‘ E ’ END
    7. 7. <ul><li>Declare is used to define local variables </li></ul><ul><li>Variable declaration is always prefixed with an ‘@’ symbol </li></ul><ul><li>Example: </li></ul>Control Flow Language – Local Variable declaration <ul><ul><li>DECLARE @mytab int </li></ul></ul><ul><ul><li>SET @mytab=1 </li></ul></ul><ul><ul><li>SELECT @mytab </li></ul></ul>
    8. 8. <ul><li>The begin and end keywords create a block for a series of statements enclosed in it. </li></ul><ul><li>In the following example, the if condition would be applicable to all the statements in the begin and end block. </li></ul><ul><li>begin…end blocks can be nested. </li></ul><ul><li>example: </li></ul>Control Flow Language – Blocks <ul><ul><ul><li>IF(SELECT sum(price) </li></ul></ul></ul><ul><ul><ul><li>FROM titles) < 200 </li></ul></ul></ul><ul><ul><ul><li>BEGIN </li></ul></ul></ul><ul><ul><ul><ul><li>UPDATE titles </li></ul></ul></ul></ul><ul><ul><ul><ul><li>SET price = price * 2 </li></ul></ul></ul></ul><ul><ul><ul><ul><li>SELECT title, price </li></ul></ul></ul></ul><ul><ul><ul><ul><li>FROM titles </li></ul></ul></ul></ul><ul><ul><ul><ul><li>WHERE price > 200 </li></ul></ul></ul></ul><ul><ul><ul><li>END </li></ul></ul></ul>
    9. 9. What is a Transaction? <ul><li>A transaction usually means a sequence of information exchange and related work (such as database updating) that is treated as a unit for the purposes of satisfying a request and for ensuring database integrity </li></ul><ul><li>For a transaction to be completed and database changes to be made permanent, a transaction has to be completed in its entirety. A program that manages or oversees the sequence of events that are part of a transaction is sometimes called a transaction monitor </li></ul><ul><li>Transactions are supported by SQL. When a transaction completes successfully, database changes are said to be committed ; when a transaction does not complete, changes are rolled back </li></ul>
    10. 10. Transaction Control <ul><li>Transaction Control Statements </li></ul><ul><ul><li>COMMIT </li></ul></ul><ul><ul><li>ROLLBACK </li></ul></ul>
    11. 11. COMMIT <ul><li>Use the COMMIT statement to end your current transaction and make permanent all changes performed in the transaction </li></ul><ul><li>If you do not explicitly commit the transaction and the program terminates abnormally, then the last uncommitted transaction is automatically rolled back </li></ul><ul><li>SYNTAX: </li></ul><ul><li>COMMIT </li></ul>
    12. 12. ROLLBACK <ul><li>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 </li></ul><ul><li>SYNTAX: </li></ul><ul><li>ROLLBACK </li></ul>
    13. 13. Transaction Example <ul><ul><li>BEGIN TRAN </li></ul></ul><ul><ul><li>INSERT INTO EMPLOYEE </li></ul></ul><ul><ul><li> (EmpId, Fname, Lname, JobId, JobLvl) </li></ul></ul><ul><ul><li>VALUES ( 'HUS42628M', 'ROGER', 'SLATE‘,12, 25) </li></ul></ul><ul><ul><li>IF(@@ERROR <> 0) </li></ul></ul><ul><ul><li>ROLLBACK TRAN </li></ul></ul><ul><ul><li>ELSE </li></ul></ul><ul><ul><li>BEGIN </li></ul></ul><ul><ul><li>DELETE FROM Jobs </li></ul></ul><ul><ul><li>WHERE jobId =13 </li></ul></ul><ul><ul><li>IF(@@ERROR <> 0) </li></ul></ul><ul><ul><li>BEGIN </li></ul></ul><ul><ul><li>PRINT 'Record not inserted in to Employee' </li></ul></ul><ul><ul><li>ROLLBACK TRAN </li></ul></ul><ul><ul><li>END </li></ul></ul><ul><ul><li>ELSE </li></ul></ul><ul><ul><li> BEGIN </li></ul></ul><ul><ul><li>PRINT 'TRANSACTION SUCCESSFUL' </li></ul></ul><ul><ul><li>COMMIT TRAN </li></ul></ul><ul><ul><li> END </li></ul></ul><ul><ul><li>END </li></ul></ul>
    14. 14. BuiltIn Variables Returns the maximum number of simultaneous user connections allowed on a Microsoft® SQL Server™. The number returned is not necessarily the number currently configured. @@MAXCONNECTION Returns the name of the language currently in use. @@LANGUAGE Returns the name of the local server running Microsoft® SQL Server™. @@SERVERNAME Returns the number of rows affected by the last statement. @@ROWCOUNT Returns the last-inserted identity value. @@IDENTITY Returns the error number for the last Transact-SQL statement executed. @@ERROR Description Variable
    15. 15. What is a Stored Procedure? <ul><li>A Stored procedure is a precompiled collection of Transact-SQL statements stored under a name and processed as a unit. </li></ul><ul><li>SQL Server supplies stored procedures for managing SQL Server and displaying information about databases and users. </li></ul><ul><li>SQL Server-supplied stored procedures are called system stored procedures. </li></ul>
    16. 16. Stored Procedures (Continued) <ul><li>A stored procedure in SQL Server is similar to a procedure in other programming languages: </li></ul><ul><ul><li>Can accept input parameters and return multiple values in the form of output parameters to the calling procedure or batch </li></ul></ul><ul><ul><li>Can contain programming statements that perform operations in the database, including calling other procedures </li></ul></ul><ul><ul><li>Can return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure) </li></ul></ul><ul><li>Note : A stored procedure is different from a function </li></ul><ul><ul><li>It do not return values in place of their names </li></ul></ul><ul><ul><li>It cannot be used directly in an expression </li></ul></ul>
    17. 17. Benefits of Stored Procedures <ul><li>Modular programming </li></ul><ul><li>Faster execution </li></ul><ul><li>Reduction in network traffic </li></ul><ul><li>Can be used as a security mechanism </li></ul>
    18. 18. Stored Procedures <ul><li>CREATE PROC [ EDURE ] procedure_name [ ; number ]      [ { @parameter data_type }          [ VARYING ] [ = default ] [ OUTPUT ] </li></ul><ul><li>] [ ,...n ] [ WITH     { RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION } ] [ FOR REPLICATION ] AS sql_statement [ ...n ] </li></ul>procedure_name is the name of the of the procedure @parameter parameter passed to the procedure data_type type of data passed to the procedure
    19. 19. Stored Procedure Example <ul><li>To execute a stored procedure use the execute command </li></ul><ul><li>Syntax : execute sp_name parameter1,parameter2…… </li></ul><ul><li>e.g. execute spAuthorDetail 4563 </li></ul><ul><ul><li>CREATE PROCEDURE spAuthorDetail </li></ul></ul><ul><ul><li> @AuthId int </li></ul></ul><ul><ul><li>AS </li></ul></ul><ul><ul><li>BEGIN </li></ul></ul><ul><ul><li>SELECT AuthorLName, </li></ul></ul><ul><ul><li> AuthorFName, </li></ul></ul><ul><ul><li>FROM Authors INNER JOIN Title </li></ul></ul><ul><ul><li>ON Authors.AuthorId = Title.AuthorId WHERE Authors.AuthorId = @AuthId </li></ul></ul><ul><ul><li>END </li></ul></ul><ul><ul><li>GO </li></ul></ul>
    20. 20. User Defined Functions <ul><li>To execute this function </li></ul>CREATE FUNCTION Addition(@Number1 Decimal(6,2), @Number2 Decimal(6,2)) RETURNS Decimal(6,2) BEGIN DECLARE @Result Decimal(6,2) SET @Result = @Number1 + @Number2 RETURN @Result END; GO SELECT dbo.addition(2,2)
    21. 21. Key Points <ul><li>SQL is an industry standard language for updating to, and getting information from, a database. </li></ul><ul><li>Transaction management is implemented in SQL using COMMIT and ROLLBACK. </li></ul><ul><li>Stored Procedures are precompiled collections of Transact-SQL statements stored under a name and processed as a unit. </li></ul>
    22. 22. Questions & Comments