Querying and Managing Data Using SQL Server 2005
Objectives


               In this session, you will learn to:
                  Implement stored procedures
                  Implement functions




    Ver. 1.0                        Session 13       Slide 1 of 19
Querying and Managing Data Using SQL Server 2005
Creating Stored Procedures


               Stored procedures:
                  Are created using the CREATE PROCEDURE statement
                  Are executed using the EXECUTE PROCEDURE statement
                  Syntax:
                   CREATE PROCEDURE proc_name
                   AS
                   BEGIN
                   sql_statement1
                   sql_statement2
                   END
               Let’s see how…




    Ver. 1.0                        Session 13                  Slide 2 of 19
Querying and Managing Data Using SQL Server 2005
Creating Stored Procedures (Contd.)


               Stored procedure:
                  Is modified using the ALTER PROCEDURE statement
                     Syntax:
                     ALTER PROCEDURE proc_name
                  Is deleted using the DROP PROCEDURE statement
                     Syntax:
                     DROP PROCEDURE proc_name
               Let’s see how…




    Ver. 1.0                       Session 13                       Slide 3 of 19
Querying and Managing Data Using SQL Server 2005
Just a minute


               Which command will you use to modify the procedure?




               Answer:
                  ALTER PROCEDURE




    Ver. 1.0                     Session 13                     Slide 4 of 19
Querying and Managing Data Using SQL Server 2005
Just a minute


               Which system-defined table stores the names of all the
               stored procedure?




               Answer:
                  sysobjects




    Ver. 1.0                     Session 13                       Slide 5 of 19
Querying and Managing Data Using SQL Server 2005
Creating Parameterized Stored Procedures


               Parameterized stored procedures:
                  Are used to pass values to the stored procedure during the run
                  time
                  Involve declaring variables and passing value to it, which is
                  defined as input parameter
               Let’s see how…




    Ver. 1.0                       Session 13                           Slide 6 of 19
Querying and Managing Data Using SQL Server 2005
Returning Values from Stored Procedures


               Stored procedure:
                  Can also return values as output
                  Uses the OUPUT keyword to specify the parameter as output
                  parameter
                  Syntax:
                   CREATE PROCEDURE procedure_name
                   [
                   {@parameter data_type}          [OUTPUT]
                   ]
                   AS
                   sql_statement [...n]
               Let’s see how…



    Ver. 1.0                       Session 13                        Slide 7 of 19
Querying and Managing Data Using SQL Server 2005
Calling a Procedure from Another Procedure


               Stored procedure:
                  Can use the values returned by a procedure inside another
                  procedure
                  That calls or executes another procedure is known as the
                  calling procedure
                  That is called or executed by the calling procedure is known as
                  the called procedure
               Let’s see how…




    Ver. 1.0                       Session 13                            Slide 8 of 19
Querying and Managing Data Using SQL Server 2005
Demo: Creating Stored Procedures


               Problem Statement:
                  You are a database developer of AdventureWorks, Inc. The
                  Human Resource department needs to revise the payment
                  details of the employees. You need to create a procedure that
                  obtains the percentage value by which you need to increase
                  the pay rate. In addition, you need to ensure that the pay is
                  revised for only those employees whose pay rate was not
                  revised in the last six months.




    Ver. 1.0                       Session 13                           Slide 9 of 19
Querying and Managing Data Using SQL Server 2005
Demo: Creating Stored Procedures (Contd.)


               Solution:
                  To solve the preceding problem, you need to perform the
                  following tasks:
                    1. Create a stored procedure.
                    2. Execute the stored procedure.
                    3. Verify the result.




    Ver. 1.0                         Session 13                        Slide 10 of 19
Querying and Managing Data Using SQL Server 2005
Creating UDFs


               Scalar functions include the following components:
                  Function name with optional schema/owner name
                  Input parameter name and data type
                  Options applicable to the input parameter
                  Return parameter data type and optional name
                  Options applicable to the return parameter
                  One or more T-SQL statements
               Scalar functions can be created by using the CREATE
               FUNCTION statement.




    Ver. 1.0                      Session 13                        Slide 11 of 19
Querying and Managing Data Using SQL Server 2005
Creating UDFs (Contd.)


                  Syntax:
                   CREATE FUNCTION [ schema_name. ] function_name
                   ( [ { @parameter_name [ AS ][ type_schema_name. ]
                     parameter_data_type
                   [ = default ] }
                   [ ,...n ]
                   ]
                   )
                   RETURNS return_data_type
                   [ WITH <function_option> [ ,...n ] ]
                   [ AS ]
                   BEGIN
                   function_body
                   RETURN scalar_expression
                   END
                   [ ; ]
               Let’s see how…

    Ver. 1.0                    Session 13                     Slide 12 of 19
Querying and Managing Data Using SQL Server 2005
Creating UDFs (Contd.)


               Table-valued functions:
                  Returns a table as an output, which can be derived as a part of
                  a SELECT statement
                  Uses the table data type to store the set of rows
                  Are of following two types:
                      Inline table-valued function
                      Multistatement table-valued function
               Let’s see how…




    Ver. 1.0                        Session 13                           Slide 13 of 19
Querying and Managing Data Using SQL Server 2005
Just a minute


               Which type of function returns a single value?




               Answer:
                   Scalar functions




    Ver. 1.0                          Session 13                Slide 14 of 19
Querying and Managing Data Using SQL Server 2005
Demo: Creating Functions


               Problem Statement:
                  As a database developer at AdventureWorks, Inc., you need to
                  create a function that accepts the employee ID of an employee
                  and returns the following details:
                   •   Employee ID
                   •   Name of the employee
                   •   Title of the employee
                   •   Number of other employees working under the employee
                  How will you create the function?




    Ver. 1.0                        Session 13                            Slide 15 of 19
Querying and Managing Data Using SQL Server 2005
Demo: Creating Functions (Contd.)


               Solution:
                   To solve the preceding problem, you need to perform the
                   following tasks:
                    1. Create a function.
                    2. Execute the function to verify the result.




    Ver. 1.0                          Session 13                       Slide 16 of 19
Querying and Managing Data Using SQL Server 2005
Summary


              In this session, you learned that:
                 A stored procedure is a collection of various T-SQL statements
                 that are stored under one name and are executed as a single
                 unit.
                 A stored procedure can be created using the CREATE
                 PROCEDURE statement.
                 A stored procedure allows you to declare parameters,
                 variables, and use T-SQL statements and programming logic.
                 A stored procedure provides better performance, security, and
                 accuracy, and reduces the network congestion.
                 A stored procedure is a collection of various T-SQL statements
                 that are stored under one name and are executed as a single
                 unit.
                 A stored procedure can be created using the CREATE
                 PROCEDURE statement.


   Ver. 1.0                       Session 13                           Slide 17 of 19
Querying and Managing Data Using SQL Server 2005
Summary (Contd.)


               A stored procedure allows you to declare parameters,
               variables, and use T-SQL statements and programming logic.
               A stored procedure provides better performance, security, and
               accuracy, and reduces the network congestion.
               A stored procedure accepts data through input parameters.
               A stored procedure returns data through the output parameters
               or return statements.
               A stored procedure can be executed by using the EXECUTE
               statement.
               A stored procedure can be altered by using the ALTER
               PROCEDURE statement.
               A user-defined function is a database object that contains a set
               of T-SQL statements.
               The user-defined functions can return either a single scalar
               value or a result set.

    Ver. 1.0                     Session 13                           Slide 18 of 19
Querying and Managing Data Using SQL Server 2005
Summary (Contd.)


               UDFs are of two types: scalar functions and table-valued
               functions.
               A scalar function accepts a single value and returns a single
               value.
               A table-valued function returns a table as an output, which can
               be derived as a part of a SELECT statement.




    Ver. 1.0                    Session 13                            Slide 19 of 19

09 qmds2005 session13

  • 1.
    Querying and ManagingData Using SQL Server 2005 Objectives In this session, you will learn to: Implement stored procedures Implement functions Ver. 1.0 Session 13 Slide 1 of 19
  • 2.
    Querying and ManagingData Using SQL Server 2005 Creating Stored Procedures Stored procedures: Are created using the CREATE PROCEDURE statement Are executed using the EXECUTE PROCEDURE statement Syntax: CREATE PROCEDURE proc_name AS BEGIN sql_statement1 sql_statement2 END Let’s see how… Ver. 1.0 Session 13 Slide 2 of 19
  • 3.
    Querying and ManagingData Using SQL Server 2005 Creating Stored Procedures (Contd.) Stored procedure: Is modified using the ALTER PROCEDURE statement Syntax: ALTER PROCEDURE proc_name Is deleted using the DROP PROCEDURE statement Syntax: DROP PROCEDURE proc_name Let’s see how… Ver. 1.0 Session 13 Slide 3 of 19
  • 4.
    Querying and ManagingData Using SQL Server 2005 Just a minute Which command will you use to modify the procedure? Answer: ALTER PROCEDURE Ver. 1.0 Session 13 Slide 4 of 19
  • 5.
    Querying and ManagingData Using SQL Server 2005 Just a minute Which system-defined table stores the names of all the stored procedure? Answer: sysobjects Ver. 1.0 Session 13 Slide 5 of 19
  • 6.
    Querying and ManagingData Using SQL Server 2005 Creating Parameterized Stored Procedures Parameterized stored procedures: Are used to pass values to the stored procedure during the run time Involve declaring variables and passing value to it, which is defined as input parameter Let’s see how… Ver. 1.0 Session 13 Slide 6 of 19
  • 7.
    Querying and ManagingData Using SQL Server 2005 Returning Values from Stored Procedures Stored procedure: Can also return values as output Uses the OUPUT keyword to specify the parameter as output parameter Syntax: CREATE PROCEDURE procedure_name [ {@parameter data_type} [OUTPUT] ] AS sql_statement [...n] Let’s see how… Ver. 1.0 Session 13 Slide 7 of 19
  • 8.
    Querying and ManagingData Using SQL Server 2005 Calling a Procedure from Another Procedure Stored procedure: Can use the values returned by a procedure inside another procedure That calls or executes another procedure is known as the calling procedure That is called or executed by the calling procedure is known as the called procedure Let’s see how… Ver. 1.0 Session 13 Slide 8 of 19
  • 9.
    Querying and ManagingData Using SQL Server 2005 Demo: Creating Stored Procedures Problem Statement: You are a database developer of AdventureWorks, Inc. The Human Resource department needs to revise the payment details of the employees. You need to create a procedure that obtains the percentage value by which you need to increase the pay rate. In addition, you need to ensure that the pay is revised for only those employees whose pay rate was not revised in the last six months. Ver. 1.0 Session 13 Slide 9 of 19
  • 10.
    Querying and ManagingData Using SQL Server 2005 Demo: Creating Stored Procedures (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Create a stored procedure. 2. Execute the stored procedure. 3. Verify the result. Ver. 1.0 Session 13 Slide 10 of 19
  • 11.
    Querying and ManagingData Using SQL Server 2005 Creating UDFs Scalar functions include the following components: Function name with optional schema/owner name Input parameter name and data type Options applicable to the input parameter Return parameter data type and optional name Options applicable to the return parameter One or more T-SQL statements Scalar functions can be created by using the CREATE FUNCTION statement. Ver. 1.0 Session 13 Slide 11 of 19
  • 12.
    Querying and ManagingData Using SQL Server 2005 Creating UDFs (Contd.) Syntax: CREATE FUNCTION [ schema_name. ] function_name ( [ { @parameter_name [ AS ][ type_schema_name. ] parameter_data_type [ = default ] } [ ,...n ] ] ) RETURNS return_data_type [ WITH <function_option> [ ,...n ] ] [ AS ] BEGIN function_body RETURN scalar_expression END [ ; ] Let’s see how… Ver. 1.0 Session 13 Slide 12 of 19
  • 13.
    Querying and ManagingData Using SQL Server 2005 Creating UDFs (Contd.) Table-valued functions: Returns a table as an output, which can be derived as a part of a SELECT statement Uses the table data type to store the set of rows Are of following two types: Inline table-valued function Multistatement table-valued function Let’s see how… Ver. 1.0 Session 13 Slide 13 of 19
  • 14.
    Querying and ManagingData Using SQL Server 2005 Just a minute Which type of function returns a single value? Answer: Scalar functions Ver. 1.0 Session 13 Slide 14 of 19
  • 15.
    Querying and ManagingData Using SQL Server 2005 Demo: Creating Functions Problem Statement: As a database developer at AdventureWorks, Inc., you need to create a function that accepts the employee ID of an employee and returns the following details: • Employee ID • Name of the employee • Title of the employee • Number of other employees working under the employee How will you create the function? Ver. 1.0 Session 13 Slide 15 of 19
  • 16.
    Querying and ManagingData Using SQL Server 2005 Demo: Creating Functions (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Create a function. 2. Execute the function to verify the result. Ver. 1.0 Session 13 Slide 16 of 19
  • 17.
    Querying and ManagingData Using SQL Server 2005 Summary In this session, you learned that: A stored procedure is a collection of various T-SQL statements that are stored under one name and are executed as a single unit. A stored procedure can be created using the CREATE PROCEDURE statement. A stored procedure allows you to declare parameters, variables, and use T-SQL statements and programming logic. A stored procedure provides better performance, security, and accuracy, and reduces the network congestion. A stored procedure is a collection of various T-SQL statements that are stored under one name and are executed as a single unit. A stored procedure can be created using the CREATE PROCEDURE statement. Ver. 1.0 Session 13 Slide 17 of 19
  • 18.
    Querying and ManagingData Using SQL Server 2005 Summary (Contd.) A stored procedure allows you to declare parameters, variables, and use T-SQL statements and programming logic. A stored procedure provides better performance, security, and accuracy, and reduces the network congestion. A stored procedure accepts data through input parameters. A stored procedure returns data through the output parameters or return statements. A stored procedure can be executed by using the EXECUTE statement. A stored procedure can be altered by using the ALTER PROCEDURE statement. A user-defined function is a database object that contains a set of T-SQL statements. The user-defined functions can return either a single scalar value or a result set. Ver. 1.0 Session 13 Slide 18 of 19
  • 19.
    Querying and ManagingData Using SQL Server 2005 Summary (Contd.) UDFs are of two types: scalar functions and table-valued functions. A scalar function accepts a single value and returns a single value. A table-valued function returns a table as an output, which can be derived as a part of a SELECT statement. Ver. 1.0 Session 13 Slide 19 of 19

Editor's Notes

  • #2 Start the session by sharing the objectives with the students.
  • #3 In this slide, you need to explain the concept of Stored Procedures to the students. Further, you will discuss the benefits of procedures – modularity, speed, security, reduced network congestion and consistency of usage across applications and users. Tell the students that since stored procedures have so many benefits, all operations and transactions from the client such as queries, updation, insertion, and deletion of rows are done using stored procedures. Even if the insert, update, delete, or query operation is very simple, a stored procedure must be created. This improves performance of the application. Hence, programmers simply execute the stored procedures, which are stored at the backend instead of sending SQL statements from the client. If the definition of the stored procedure needs to be modified, then use the ALTER PROCEDURE statement. You can use the examples given in the Student Guide to clarify the concept to the students. Further, you can execute the following statements to explain the concept: Example: CREATE PROCEDURE prcDept AS BEGIN SELECT Name FROM HumanResources.Department END Executing the procedure EXECUTE prcDept Additional Inputs When designing an application, stored procedures can significantly reduce the network requirements. Use stored procedures for long, complicated, and frequently repeated queries. This reduces the traffic from the client to the server because only the stored procedure name and its associated parameters are passed across the network to the server, where it is executed. In addition, multi-step queries that perform additional filtering or processing based upon the response to initial queries, run much more efficiently as a stored procedure. By using a stored procedure, it is not necessary to pass the results of the initial query to the client in order that a second query can be passed to the server. The sp_depends stored procedure can be used to find out the dependencies of a stored procedure. The syntax is as given below: sp_depends object_name
  • #4 In this slide, you will tell the students about altering and dropping a stored procedure. You can use the examples given in the Student Guide to clarify the concept to the students. Further, you can execute the following statements to explain the concept: Example: (ALTER) ALTER PROCEDURE prcDept AS BEGIN SELECT DepartmentID, Name FROM HumanResources.Department END Example: (DROP) DROP PROCEDURE pcrDept
  • #5 Reiterate the concepts taught in the preceding slides by asking the question.
  • #6 Reiterate the concepts taught in the preceding slides by asking the question.
  • #7 In this slide, you need to explain about parameterized stored procedures. After explaining the two types of parameters, tell the students that a procedure with output parameters is typically executed from another calling procedure. Mention that the ‘return’ keyword is used when a single value needs to be returned to the calling program. Output parameters are used when multiple values of any data type have to be returned. Tell the students that apart from explicitly executing a stored procedure it can be executed automatically, for example, at the start-up of SQL Server. This can be done by using a system stored procedure called sp_procoption for only objects of master database, which are owned by dbo. The syntax for sp_procoption procedure is shown below: sp_procoption @ProcName = &apos; procedure &apos;, @OptionName = &apos; option &apos;, @OptionValue = &apos; value &apos; where, @ProcName defines the procedure for which to set the option @OptionName defines the option to set for the procedure that can only be ‘startup’, which will set the procedure for autoexecution @OptionValue defines whether to set the option as true or false Procedure Usage Mention in the class that if data changes and indexes are updated, the execution plan for the SQL statements in a stored procedure will become outdated. In this kind of a situation, the SQL statement needs to be recompiled every time the stored procedure gets executed. This is done using the WITH RECOMPILE option of the CREATE PROCEDURE statement. Remember to use naming conventions while creating procedures. Refer SG for explanation Example: CREATE PROC prcListEmployee @title char(50) AS BEGIN PRINT &apos;List of Employees&apos; SELECT EmployeeID, LoginID, Title FROM HumanResources.Employee WHERE Title = @title END Execute by passing a parameter EXECUTE prcListEmployee &apos;Tool Designer&apos;
  • #8 Example: CREATE PROCEDURE prcGetEmployeeDetail @EmpId int, @DepId int OUTPUT, @DepName char(50) OUTPUT, @ShiftId int OUTPUT AS BEGIN IF EXISTS(SELECT * FROM HumanResources.Employee WHERE EmployeeID = @EmpId) BEGIN SELECT @DepId = d.DepartmentID, @DepName = Name, @ShiftId = ShiftID FROM HumanResources.Department d JOIN HumanResources.EmployeeDepartmentHistory h ON d.DepartmentID = h.DepartmentID WHERE EmployeeID = @EmpId RETURN 0 END ELSE RETURN 1 END
  • #9 In this slide, you need to tell the students about calling a procedure from another. Additional Inputs Notice that whenever a procedure gets called from within another procedure you have to use the EXEC keyword. Example: CREATE PROCEDURE prcDisplayEmployeeStatus @EmpId int AS BEGIN DECLARE @DepId int DECLARE @DepName char(50) DECLARE @ShiftId int DECLARE @ReturnValue int EXEC @ReturnValue = prcGetEmployeeDetail @EmpId, @DepId output, @DepName output, @ShiftId output IF (@ReturnValue = 0) BEGIN PRINT &apos;The Details of an Employee having ID: &apos; + CONVERT(char(10), @EmpId) PRINT &apos;Department ID: &apos; + CONVERT( char(10), @DepId) PRINT &apos;Department Name: &apos; + @DepName PRINT &apos;Shift ID: &apos; + CONVERT( char(10), @ShiftId) Select ManagerID, Title from HumanResources.Employee Where EmployeeID = @EmpID END ELSE PRINT &apos;No records found for the given Employee&apos; END Executing the procedure: To execute the above procedure, you need to execute the following statement: EXEC PrcDisplayEmployeeStatus 2
  • #10 You need to ensure that after this demo, students are able to create and execute stored procedure.
  • #12 In this slide, you need to explain the user-defined functions first. In addition, state that User-Defined functions are of two types, Scalar Functions and Table-Valued Functions. In addition, you need to explain about Scalar Functions and creating Scalar Function.
  • #13 Example: CREATE FUNCTION HumanResources.MonthlySal ( @PayRate float) RETURNS float AS BEGIN RETURN (@PayRate * 8 * 30) END DECLARE @PayRate float SET @PayRate = HumanResources.MonthlySal(12.25) PRINT @PayRate
  • #14 In this slide, you need to explain the students about Table-Value Functions. Example: (inline table-valued function) USE AdventureWorks go CREATE FUNCTION fx_Department_GName ( @GrName nvarchar(20) ) RETURNS table AS RETURN ( SELECT * FROM HumanResources.Department WHERE GroupName=@GrName ) go After creating the function, calling the function with specified argument. SELECT * FROM fx_Department_GName(&apos;Manufacturing&apos;) Example: (multistatement table-valued function) CREATE FUNCTION PayRate (@rate money) RETURNS @table TABLE (EmployeeID int not null, RateChangeDate datetime not null, Rate money not null, PayFrequency tinyint not null, ModifiedDate datetime not null) AS BEGIN INSERT @table SELECT * FROM HumanResources.EmployeePayHistory WHERE Rate &gt; @rate RETURN END Select * from PayRate(45)
  • #15 Reiterate the learning by asking the given question.
  • #16 You need to ensure that after this demo, the students are able to create and execute user-defined functions.
  • #18 You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  • #19 You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  • #20 You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.