SlideShare a Scribd company logo
1 of 61
Implementing Stored Procedures

Objectives
In this lesson, you will learn to:
 Create a stored procedure
 Execute a stored procedure
 Pass parameters to a stored procedure
 Modify a stored procedure
 Return values from a stored procedure
 Return multiple values from a stored procedure
 Call a procedure from another stored procedure
 Recompile a stored procedure
 Drop a stored procedure
©NIIT                                      SQL/Lesson 9/Slide 1 of 61
Implementing Stored Procedures

Getting Started
 A stored procedure is a collection or batch of T-SQL
  statements and control-of-flow language that is stored under
  one name, and executed as a single unit
 Benefits of Stored Procedures
   Improved performance
   Reduction in network congestion
   Better consistency
   Better security mechanism




©NIIT                                       SQL/Lesson 9/Slide 2 of 61
Implementing Stored Procedures

Getting Started (Contd.)
 Types of Procedures
     User-defined
     System
     Temporary
     Remote
     Extended




©NIIT                            SQL/Lesson 9/Slide 3 of 61
Implementing Stored Procedures

Just a Minute…
 What are the benefits of using stored procedures?




©NIIT                                      SQL/Lesson 9/Slide 4 of 61
Implementing Stored Procedures

9.D.1 Speeding up the Execution of Batch Statements
 A list containing the name, address, city, zip code, telephone
  number, and the fax number of recruitment agencies is
  required frequently. Recently, it has been noticed that there
  is a delay in generating this report due to the network
  congestion. Besides, the Human Resources department
  personnel make mistakes while querying for this information.
  Suggest and implement a solution.




©NIIT                                        SQL/Lesson 9/Slide 5 of 61
Implementing Stored Procedures

Task List
 Identify the object that can be used to solve the above
  problem
 Draft the stored procedure on paper
 Create the stored procedure in the database
 Check the existence of the procedure in the database
 Execute the procedure




©NIIT                                        SQL/Lesson 9/Slide 6 of 61
Implementing Stored Procedures

Identify the object that can be used to solve the above
Problem
 Result:
    Use a stored procedure to reduce network traffic and reduce
     the errors committed by the HR personnel




 ©NIIT                                       SQL/Lesson 9/Slide 7 of 61
Implementing Stored Procedures

Draft the stored procedure on paper
 The CREATE PROCEDURE Statement
     Syntax
      CREATE PROCEDURE proc_name
      AS
      BEGIN
       sql_statement1
       sql_statement2
       END




©NIIT                                 SQL/Lesson 9/Slide 8 of 61
Implementing Stored Procedures

Draft the stored procedure on paper (Contd.)
 Result:
     The database in which the stored procedure has to be
      created is Recruitment
     The type of procedure is user-defined
     The name for the stored procedure is
      prcPrintRecruitmentAgencyList




©NIIT                                         SQL/Lesson 9/Slide 9 of 61
Implementing Stored Procedures
Create the stored procedure in the database
 Action:
     In the Query Analyzer window, type:
      CREATE PROCEDURE
               prcPrintRecruitmentAgencyList
      AS
      BEGIN
      PRINT 'List of Recruitment Agencies'
      SELECT cName, vAddress, cCity, cZip,
       cPhone, cFax
      FROM RecruitmentAgencies
      END
     Press F5 to execute the statement

©NIIT                                     SQL/Lesson 9/Slide 10 of 61
Implementing Stored Procedures

Check the existence of the procedure in the database
 The sp_helptext Command is used to check the existence of
  a procedure in the database
 Syntax
  sp_helptext proc_name
 Action
     In the Query Analyzer window, type:
        sp_helptext prcPrintRecruitmentAgencyList
     Check the result. The output must be the code that you
      wrote to create the procedure

©NIIT                                       SQL/Lesson 9/Slide 11 of 61
Implementing Stored Procedures

Execute the procedure
 The EXECUTE PROCEDURE statement is used to execute
  the stored procedure
 Syntax
  EXECUTE proc_name
  or
  EXEC proc_name
  or
  proc_name



 ©NIIT                               SQL/Lesson 9/Slide 12 of 61
Implementing Stored Procedures

Execute the procedure (Contd.)
 Action:
     In the Query Analyzer window, type:
        EXECUTE prcPrintRecruitmentAgencyList
        or
        EXEC prcPrintRecruitmentAgencyList
        or
        prcPrintRecruitmentAgencyList
     Press F5 to execute the command


©NIIT                                       SQL/Lesson 9/Slide 13 of 61
Implementing Stored Procedures

Just a Minute…
 The query to obtain the list of candidates and their
  recruitment agencies is:
  SELECT 'Candidate Name' = vFirstName ,
  'Recruitment Agency' = cName
  FROM ExternalCandidate
  JOIN RecruitmentAgencies
  ON ExternalCAndidate.cAgencyCode =
  RecruitmentAgencies.cAgencyCode
 Create a stored procedure for the same.



©NIIT                                        SQL/Lesson 9/Slide 14 of 61
Implementing Stored Procedures

9.D.2 Creating a Generic Stored Procedure
 Information on contract recruiters in a particular city is
  required frequently.The city for which details are required
  changes from time to time. Create a stored procedure that
  will generate information for a specified city




©NIIT                                       SQL/Lesson 9/Slide 15 of 61
Implementing Stored Procedures

Task List
 Identify a method to write a generic procedure that will
  generate results for variable inputs
 Draft statements to create a procedure
 Create the stored procedure in the database
 Check the existence of the procedure in the database
 Prepare test cases with existing and non-existing values
 Execute the procedure with the existing value
 Execute the procedure with the non-existing value



 ©NIIT                                        SQL/Lesson 9/Slide 16 of 61
Implementing Stored Procedures

Identify a method to write a generic procedure that
will generate results for variable inputs
 Parameter
     A parameter is a placeholder in a query or a stored
      procedure that accepts a user-defined value whenever
      the query or stored procedure is executed
 Types of Parameters
     Input parameters
     Output parameters
 Result:
     As the city name will be supplied by the user, use input
      parameters

©NIIT                                        SQL/Lesson 9/Slide 17 of 61
Implementing Stored Procedures

Draft statements to create a procedure
 Result:
     The variable name is @cCity
     The datatype of the variable is char of size 15. So, the
      variable needs to be declared, as shown below:
        @cCity char(15)




©NIIT                                         SQL/Lesson 9/Slide 18 of 61
Implementing Stored Procedures

Create the stored procedure in the database
 Action:
     In the Query Analyzer window, type:
      CREATE PROC prcListContractRecruiter
      @cCity char(15)
      AS
      BEGIN
        PRINT 'List of Contract Recruiters'
        SELECT cName,cCity,cZip,cPhone
        FROM ContractRecruiter
        WHERE cCity = @cCity
      END
     Press F5 to execute the query
©NIIT                                SQL/Lesson 9/Slide 19 of 61
Implementing Stored Procedures

Check the existence of the procedure in the database
Action:
     In the Query Analyzer window, type:
        sp_helptext prcListContractRecruiter
     Check the result
Prepare test cases with the existing and non-existing
values
Action:
     Test for a city, which exists in the ContractRecruiter table:
      Alexandria
     Test for a city, which does not exist in the ContractRecruiter
      table: Boston
©NIIT                                         SQL/Lesson 9/Slide 20 of 61
Implementing Stored Procedures

Execute the procedure with the existing value
 Action:
     In the Query Analyzer window, type:
        prcListContractRecruiter Alexandria
     Press F5 to execute the procedure
Execute the procedure with the non-existing value
 Action:
     In the Query Analyzer window, type:
        prcListContractRecruiter Boston
     Press F5 to execute the procedure

©NIIT                                       SQL/Lesson 9/Slide 21 of 61
Implementing Stored Procedures

9.D.3 Modifying a Stored Procedure
 Details of the recruitment agencies for a particular city are
  required. The city for which the data is required varies from
  time to time. Instead of creating a new procedure, modify the
  existing prcPrintRecruitmentAgencyList procedure to meet
  this requirement. In the new procedure, if no value is passed
  to the procedure, it should display 'Usage:
  prcPrintRecruitmentAgencyList city' and stop execution.




©NIIT                                       SQL/Lesson 9/Slide 22 of 61
Implementing Stored Procedures

Task List
 Identify a method to modify the existing procedure
 Draft statements to modify a procedure
 Verify that the procedure has been modified
 Execute the procedure




©NIIT                                      SQL/Lesson 9/Slide 23 of 61
Implementing Stored Procedures

Identify a method to modify the existing procedure
 The ALTER PROCEDURE Statement is used to modify an
  existing procedure.
 The Default Parameter
     You can use default parameters to pass value to the
      stored procedure in case no value is passed to it.
     The value passed as default value must be a constant
      value or NULL.
 Result:
     Use the ALTER PROCEDURE statement to modify the
      procedure.


©NIIT                                      SQL/Lesson 9/Slide 24 of 61
Implementing Stored Procedures

Identify a method to modify the existing procedure
(Contd.)
     Use NULL as the default parameter to the procedure. If
      no value is passed to the procedure parameter, the
      parameter would contain a NULL value. If the value of the
      parameter is NULL, the procedure should display a
      message explaining the usage of the procedure.
Draft statements to modify a procedure
 Action:
     In the Query Analyzer window, type:
        ALTER PROCEDURE prcPrintRecruitmentAgencyList
        @city char(15)=NULL

©NIIT                                       SQL/Lesson 9/Slide 25 of 61
Implementing Stored Procedures

Draft statements to modify a procedure (Contd.)
        AS
        BEGIN
        IF @city is null
        BEGIN
         PRINT 'Usage:
         prcPrintRecruitmentAgencyList city'
         RETURN
        END
        PRINT 'List of Recruitment Agencies'
        SELECT cName,vAddress,cZip,cPhone
        FROM RecruitmentAgencies
        WHERE cCity = @city
©NIIT
        END                          SQL/Lesson 9/Slide 26 of 61
Implementing Stored Procedures

Draft statements to modify a procedure (Contd.)
     Press F5 to execute the query
     In the above code, the RETURN statement passes the
      control back to the position from where it was called




©NIIT                                      SQL/Lesson 9/Slide 27 of 61
Implementing Stored Procedures

Verify that the procedure has been modified
 Action:
     In the Query Analyzer window, type:
        sp_helptext prcPrintrecruitmentAgencyList
     Press F5 to execute the query
Execute the procedure
 Action:
     In the Query Analyzer window, type:
        EXEC prcPrintRecruitmentAgencyList
        Alexandria
     Press F5 to execute the query
©NIIT                                       SQL/Lesson 9/Slide 28 of 61
Implementing Stored Procedures

Execute the procedure (Contd.)
     In case you do not pass any parameter to the procedure
      by typing:
        prcPrintRecruitmentAgencyList
        you will get the following output:
        Usage: prcPrintRecruitmentAgencyList
         city




©NIIT                                        SQL/Lesson 9/Slide 29 of 61
Implementing Stored Procedures

9.D.4 Notifying Successful Execution
 Modify the prcPrintRecruitmentAgencyList procedure to
  notify users of its successful execution




©NIIT                                     SQL/Lesson 9/Slide 30 of 61
Implementing Stored Procedures

Task List
 Identify a method to write a procedure that will return a value
 Draft the procedure
 Modify the procedure in the database
 Check that the procedure has been modified in the database
 Execute the procedure




©NIIT                                         SQL/Lesson 9/Slide 31 of 61
Implementing Stored Procedures

Identify a method to write a procedure that will return
a value
 The RETURN Keyword
     You use the RETURN statement to return values from a
      stored procedure
 Syntax
   RETURN value
 Result:
   The RETURN statement can be used to return values from a
   stored procedure


 ©NIIT                                    SQL/Lesson 9/Slide 32 of 61
Implementing Stored Procedures

Draft the procedure
 Result:
     The batch statements for creating the stored procedure
      are as follows:
    ALTER PROCEDURE
      prcPrintRecruitmentAgencyList @city
      char(15)
    AS
    BEGIN
    IF EXISTS(SELECT * FROM RecruitmentAgencies

    WHERE cCity=@city)
©NIIT                                       SQL/Lesson 9/Slide 33 of 61
Implementing Stored Procedures

Draft the procedure (Contd.)
    BEGIN
    PRINT 'List of Recruitment Agencies'
    SELECT cName,vAddress,cZip,cPhone
    FROM RecruitmentAgencies
    WHERE cCity = @city
    Return 0
    END
    ELSE BEGIN
    PRINT 'No Records Found for given city' RETURN 1
    END
    END
©NIIT                                   SQL/Lesson 9/Slide 34 of 61
Implementing Stored Procedures

Modify the procedure in the database
 Action:
     In the Query Analyzer window, type
      prcPrintRecruitmentAgencyList
     Press F5 to execute the statement




©NIIT                                     SQL/Lesson 9/Slide 35 of 61
Implementing Stored Procedures

Check that the procedure has been modified in the
database
Action:
         In the Query Analyzer window, type:
          sp_helptext
          prcPrintRecruitmentAgencyList
         Press F5 to execute the statement




©NIIT                                           SQL/Lesson 9/Slide 36 of 61
Implementing Stored Procedures

Execute the procedure
 Action:
     In the Query Analyzer window, type:
        DECLARE @ReturnValue int
        EXEC @ReturnValue =
        prcPrintRecruitmentAgencyList 'Alexandria'
        SELECT @ReturnValue
     Press F5 to execute the statement. When the above
      statements are executed, the value returned by the
      procedure prcPrintRecruitmentAgencyList would be
      stored in the variable @ReturnValue. This value would be
      displayed by the SELECT statement
©NIIT                                       SQL/Lesson 9/Slide 37 of 61
Implementing Stored Procedures

9.D.5 Calling One Procedure From Another
 Details about the recruitment agencies and the contract
  recruiters in a city are required in a single report. Create a
  single procedure that uses the existing procedures for the
  report




©NIIT                                        SQL/Lesson 9/Slide 38 of 61
Implementing Stored Procedures

Task List
 Identify a method to modify the existing procedure
 Create the procedure in the database
 Check the existence of the procedure in the database
 Execute the procedure with parameters




©NIIT                                       SQL/Lesson 9/Slide 39 of 61
Implementing Stored Procedures

Identify a method to write a procedure that will use an
existing procedure
 Nested Procedures
         You can execute or call one procedure from within
          another procedure
 Result:
         Create a new stored procedure that will call the existing
          procedures




©NIIT                                           SQL/Lesson 9/Slide 40 of 61
Implementing Stored Procedures

Create the procedure in the database
 Action:
     In the Query Analyzer window, type:
        CREATE PROCEDURE prcDisplayBoth
        @city char(15)
        AS
        BEGIN
        EXEC prcListContractRecruiter @city
        EXEC prcPrintRecruitmentAgencyList @city
        END
     Press F5 to execute the statement

©NIIT                                       SQL/Lesson 9/Slide 41 of 61
Implementing Stored Procedures

Check the existence of the procedure in the database
 Action:
    In the Query Analyzer window, type:
      sp_helptext prcDisplayBoth
     Press F5 to execute the statement

Execute the procedure with parameters
 Action:
     In the Query Analyzer window, type:
        prcDisplayBoth 'Alexandria'
     Press F5 to execute the statement


©NIIT                                       SQL/Lesson 9/Slide 42 of 61
Implementing Stored Procedures

Just a Minute…
 You need to modify a stored procedure. Which command will
  you use to modify the procedure?




©NIIT                                    SQL/Lesson 9/Slide 43 of 61
Implementing Stored Procedures

9.D.6 Returning Multiple Output Values
A formatted report of the status of positions available in
 the company is to be displayed. Create a procedure,
 prcGetPositionDetail which will return the position
 description, the budgeted manpower and the current
 strength of employees for a given position. Create another
 procedure called prcDisplayPositionStatus that will display
 cRequisitionCode, vRegion, and siNoOfVacancy from the
 Requisition table. The procedure prcDisplayPositionStatus
 should also call the prcGetPositionDetail procedure and
 display the values returned by it for position '0002' in the
 following format:


©NIIT                                      SQL/Lesson 9/Slide 44 of 61
Implementing Stored Procedures

9.D.6 Returning Multiple Output Values (Contd.)
The Status for the Position: Maketing            Manager


Budgeted Strength             : 100


Current Strength              : 83


cRequisitionCode vRegion                 siNoOfVacancy
---------------- -------------------- ----------
000002             Texas                       11


©NIIT                                 SQL/Lesson 9/Slide 45 of 61
Implementing Stored Procedures

Task List
 Identify a method to write a generic procedure that will return
  more than one value
 Create the procedure in the database
 Check whether the procedure exists in the database
 Execute the procedure with parameters




 ©NIIT                                        SQL/Lesson 9/Slide 46 of 61
Implementing Stored Procedures

Identify a method to write a generic procedure that
will return more than one value
 The OUTPUT Parameter - is used to return more than one
  value from the procedure
 Syntax
  CREATE PROC[EDURE] procedure_name
  [ {@parameter data_type}   [OUTPUT]
  ]
  AS
  sql_statement [...n]
     Result:
        ® Use   CREATE PROCEDURE with the OUTPUT option

©NIIT                                    SQL/Lesson 9/Slide 47 of 61
Implementing Stored Procedures

Create the procedure in the database
 Action:
     In the Query Analyzer Window, type the statements given
      below.
      CREATE PROCEDURE prcGetPositionDetail
              @Pcode char(4),
             @Description char(30) OUTPUT,
             @budget int OUTPUT,
              @CurrentStrength int OUTPUT
      AS
      BEGIN
      IF EXISTS(SELECT * FROM Position WHERE
      cPositionCode = @PCode)
©NIIT                                      SQL/Lesson 9/Slide 48 of 61
Implementing Stored Procedures

Create the procedure in the database (Contd.)
        BEGIN
           SELECT @Description =
           vDescription,@budget =
           iBudgetedStrength,
           @CurrentStrength = iCurrentStrength
          FROM Position
          WHERE cPositionCode=@Pcode
          RETURN 0
        END
        ELSE
           RETURN 1
        END
     Press F5 to execute
©NIIT                                SQL/Lesson 9/Slide 49 of 61
Implementing Stored Procedures

Create the procedure in the database (Contd.)
     In the Query Analyzer Window, type:
        CREATE PROCEDURE prcDisplayPositionStatus
        @PCode char(4)
        AS
        BEGIN
        DECLARE @Description char(30)
        DECLARE @budget int
        DECLARE @CurrentStrength int
        DECLARE @ReturnValue int
        EXEC @ReturnValue = prcGetPositionDetail
        @Pcode,
        @Description output,
        @Budget output,
        @CurrentStrength output
©NIIT                                       SQL/Lesson 9/Slide 50 of 61
Implementing Stored Procedures

Create the procedure in the database (Contd.)
        IF (@ReturnValue = 0)
        BEGIN
          PRINT 'The Status for the Position: '
          + @Description
          PRINT 'Budgeted Strength : '    +
          CONVERT( char(30), @budget)
          PRINT 'Current Strength   : ' + CONVERT
          (char(30), @CurrentStrength)
          SELECT cRequisitionCode,vRegion,
          siNoOfVacancy FROM Requisition WHERE
          cPositionCode=@Pcode
©NIIT                               SQL/Lesson 9/Slide 51 of 61
Implementing Stored Procedures

Create the procedure in the database (Contd.)
       END
       ELSE
        PRINT 'No records for the given position
        code'
       END
     Press F5 to execute




©NIIT                             SQL/Lesson 9/Slide 52 of 61
Implementing Stored Procedures

Check whether the procedure exists in the database
 In the Query Analyzer window, type and execute the
  following statements:
  sp_helptext prcGetPositionDetail
  go
  sp_helptext prcDisplayPositionStatus
  go




©NIIT                                     SQL/Lesson 9/Slide 53 of 61
Implementing Stored Procedures

Execute the procedure with parameters
 Action:
     In the Query Analyzer window, type:
        prcDisplayPositionstatus '0002'
     Press F5 to execute
     Verify that the required output is displayed




©NIIT                                         SQL/Lesson 9/Slide 54 of 61
Implementing Stored Procedures

The RECOMPILE Option
 To generate an updated execution plan, you must recompile
  the stored procedure, each time you execute the stored
  procedure
 Syntax
  CREATE PROCEDURE       proc_name     [WITH RECOMPILE]
  AS
  sql_statements




©NIIT                                    SQL/Lesson 9/Slide 55 of 61
Implementing Stored Procedures

The DROP PROCEDURE Statement
 Is used to drop a stored procedure from the database
 Syntax
  DROP PROCEDURE proc_name
 You cannot retrieve a procedure once it is dropped




©NIIT                                      SQL/Lesson 9/Slide 56 of 61
Implementing Stored Procedures

Extended Stored Procedures
 Allow you to create your own external routines in a
  programming language such as C
 Are Dynamic-Link Libraries (DLLs) that SQL Server can
  dynamically load and execute




©NIIT                                       SQL/Lesson 9/Slide 57 of 61
Implementing Stored Procedures

Summary
In this lesson, you learned that:
 A stored procedure is a collection of various T-SQL statements
  that are stored under one name and executed as a single unit
 A stored procedure can be created either in the Enterprise
  Manager or in the Query Analyzer window with 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 network congestion

©NIIT                                      SQL/Lesson 9/Slide 58 of 61
Implementing Stored Procedures

Summary (Contd.)
 The various types of stored procedures are:
     User-defined
     System
     Temporary
     Remote
     Extended
 A stored procedure accepts and returns data through the
  following:
     Input parameters
©NIIT                                      SQL/Lesson 9/Slide 59 of 61
Implementing Stored Procedures

Summary (Contd.)
     Output parameters
     Return statements
 A stored procedure can be executed using the EXECUTE
  statement
 A stored procedure can be altered using the ALTER
  PROCEDURE statement

 A stored procedure can be viewed using the sp_help and the
  sp_helptext system procedures
 To generate an updated execution plan, you must recompile
  the stored procedure each time you execute the stored
  procedure
©NIIT                                     SQL/Lesson 9/Slide 60 of 61
Implementing Stored Procedures

Summary (Contd.)
 To recompile a stored procedure automatically, you must create
  the stored procedure with a WITH RECOMPILE option
 A stored procedure can be dropped using the DROP
  PROCEDURE statement
 Extended stored procedures are Dynamic-Link Libraries (DLLs)
  that SQL Server can dynamically load and execute




 ©NIIT                                     SQL/Lesson 9/Slide 61 of 61

More Related Content

Viewers also liked

02 iec t1_s1_plt_session_02
02 iec t1_s1_plt_session_0202 iec t1_s1_plt_session_02
02 iec t1_s1_plt_session_02Niit Care
 
Comp tia n+_session_08
Comp tia n+_session_08Comp tia n+_session_08
Comp tia n+_session_08Niit Care
 
01 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_0101 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_01Niit Care
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architectureAjeet Singh
 

Viewers also liked (9)

Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 b
 
02 iec t1_s1_plt_session_02
02 iec t1_s1_plt_session_0202 iec t1_s1_plt_session_02
02 iec t1_s1_plt_session_02
 
Comp tia n+_session_08
Comp tia n+_session_08Comp tia n+_session_08
Comp tia n+_session_08
 
01 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_0101 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_01
 
SQL | Computer Science
SQL | Computer ScienceSQL | Computer Science
SQL | Computer Science
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 
Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
 

Similar to Sql xp 09

Online_Examination
Online_ExaminationOnline_Examination
Online_ExaminationRupam Dey
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Sparkhound Inc.
 
Winter Simulation Conference 2021 - Process Wind Tunnel Talk
Winter Simulation Conference 2021 - Process Wind Tunnel TalkWinter Simulation Conference 2021 - Process Wind Tunnel Talk
Winter Simulation Conference 2021 - Process Wind Tunnel TalkSudhendu Rai
 
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxCASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxketurahhazelhurst
 
Towards explanations for Data-Centric AI using provenance records
Towards explanations for Data-Centric AI using provenance recordsTowards explanations for Data-Centric AI using provenance records
Towards explanations for Data-Centric AI using provenance recordsPaolo Missier
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02Vivek chan
 
How Manual Testers Can Break into Automation Without Programming Skills
How Manual Testers Can Break into Automation Without Programming SkillsHow Manual Testers Can Break into Automation Without Programming Skills
How Manual Testers Can Break into Automation Without Programming SkillsRanorex
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG Greg.Helton
 
Oracle - Checklist for performance issues
Oracle - Checklist for performance issuesOracle - Checklist for performance issues
Oracle - Checklist for performance issuesMarkus Flechtner
 
7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script TaskPramod Singla
 
OpenDaylight app development tutorial
OpenDaylight app development tutorialOpenDaylight app development tutorial
OpenDaylight app development tutorialSDN Hub
 
单元测试必知必会
单元测试必知必会单元测试必知必会
单元测试必知必会智杰 付
 
Guide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in KotlinGuide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in KotlinRapidValue
 
Flink Forward San Francisco 2018: David Reniz & Dahyr Vergara - "Real-time m...
Flink Forward San Francisco 2018:  David Reniz & Dahyr Vergara - "Real-time m...Flink Forward San Francisco 2018:  David Reniz & Dahyr Vergara - "Real-time m...
Flink Forward San Francisco 2018: David Reniz & Dahyr Vergara - "Real-time m...Flink Forward
 
Quick Test Professional (QTP/UFT)
Quick Test Professional (QTP/UFT)Quick Test Professional (QTP/UFT)
Quick Test Professional (QTP/UFT)Rajathi-QA
 
Evaluating Test Driven Development And Parameterized Unit Testing In Dot Net ...
Evaluating Test Driven Development And Parameterized Unit Testing In Dot Net ...Evaluating Test Driven Development And Parameterized Unit Testing In Dot Net ...
Evaluating Test Driven Development And Parameterized Unit Testing In Dot Net ...mdfachowdhury
 
Acutate - Using Stored Procedure
Acutate - Using Stored ProcedureAcutate - Using Stored Procedure
Acutate - Using Stored ProcedureAishwarya Savant
 

Similar to Sql xp 09 (20)

Online_Examination
Online_ExaminationOnline_Examination
Online_Examination
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Winter Simulation Conference 2021 - Process Wind Tunnel Talk
Winter Simulation Conference 2021 - Process Wind Tunnel TalkWinter Simulation Conference 2021 - Process Wind Tunnel Talk
Winter Simulation Conference 2021 - Process Wind Tunnel Talk
 
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxCASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
 
Towards explanations for Data-Centric AI using provenance records
Towards explanations for Data-Centric AI using provenance recordsTowards explanations for Data-Centric AI using provenance records
Towards explanations for Data-Centric AI using provenance records
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02
 
How Manual Testers Can Break into Automation Without Programming Skills
How Manual Testers Can Break into Automation Without Programming SkillsHow Manual Testers Can Break into Automation Without Programming Skills
How Manual Testers Can Break into Automation Without Programming Skills
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG
 
Oracle - Checklist for performance issues
Oracle - Checklist for performance issuesOracle - Checklist for performance issues
Oracle - Checklist for performance issues
 
7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task
 
OpenDaylight app development tutorial
OpenDaylight app development tutorialOpenDaylight app development tutorial
OpenDaylight app development tutorial
 
I07 Simulation
I07 SimulationI07 Simulation
I07 Simulation
 
I07 Simulation
I07 SimulationI07 Simulation
I07 Simulation
 
单元测试必知必会
单元测试必知必会单元测试必知必会
单元测试必知必会
 
Guide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in KotlinGuide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in Kotlin
 
Flink Forward San Francisco 2018: David Reniz & Dahyr Vergara - "Real-time m...
Flink Forward San Francisco 2018:  David Reniz & Dahyr Vergara - "Real-time m...Flink Forward San Francisco 2018:  David Reniz & Dahyr Vergara - "Real-time m...
Flink Forward San Francisco 2018: David Reniz & Dahyr Vergara - "Real-time m...
 
Quick Test Professional (QTP/UFT)
Quick Test Professional (QTP/UFT)Quick Test Professional (QTP/UFT)
Quick Test Professional (QTP/UFT)
 
Evaluating Test Driven Development And Parameterized Unit Testing In Dot Net ...
Evaluating Test Driven Development And Parameterized Unit Testing In Dot Net ...Evaluating Test Driven Development And Parameterized Unit Testing In Dot Net ...
Evaluating Test Driven Development And Parameterized Unit Testing In Dot Net ...
 
Acutate - Using Stored Procedure
Acutate - Using Stored ProcedureAcutate - Using Stored Procedure
Acutate - Using Stored Procedure
 

More from Niit Care (20)

Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 a
 

Recently uploaded

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

Sql xp 09

  • 1. Implementing Stored Procedures Objectives In this lesson, you will learn to: Create a stored procedure Execute a stored procedure Pass parameters to a stored procedure Modify a stored procedure Return values from a stored procedure Return multiple values from a stored procedure Call a procedure from another stored procedure Recompile a stored procedure Drop a stored procedure ©NIIT SQL/Lesson 9/Slide 1 of 61
  • 2. Implementing Stored Procedures Getting Started A stored procedure is a collection or batch of T-SQL statements and control-of-flow language that is stored under one name, and executed as a single unit Benefits of Stored Procedures Improved performance Reduction in network congestion Better consistency Better security mechanism ©NIIT SQL/Lesson 9/Slide 2 of 61
  • 3. Implementing Stored Procedures Getting Started (Contd.) Types of Procedures User-defined System Temporary Remote Extended ©NIIT SQL/Lesson 9/Slide 3 of 61
  • 4. Implementing Stored Procedures Just a Minute… What are the benefits of using stored procedures? ©NIIT SQL/Lesson 9/Slide 4 of 61
  • 5. Implementing Stored Procedures 9.D.1 Speeding up the Execution of Batch Statements A list containing the name, address, city, zip code, telephone number, and the fax number of recruitment agencies is required frequently. Recently, it has been noticed that there is a delay in generating this report due to the network congestion. Besides, the Human Resources department personnel make mistakes while querying for this information. Suggest and implement a solution. ©NIIT SQL/Lesson 9/Slide 5 of 61
  • 6. Implementing Stored Procedures Task List Identify the object that can be used to solve the above problem Draft the stored procedure on paper Create the stored procedure in the database Check the existence of the procedure in the database Execute the procedure ©NIIT SQL/Lesson 9/Slide 6 of 61
  • 7. Implementing Stored Procedures Identify the object that can be used to solve the above Problem Result: Use a stored procedure to reduce network traffic and reduce the errors committed by the HR personnel ©NIIT SQL/Lesson 9/Slide 7 of 61
  • 8. Implementing Stored Procedures Draft the stored procedure on paper The CREATE PROCEDURE Statement Syntax CREATE PROCEDURE proc_name AS BEGIN sql_statement1 sql_statement2 END ©NIIT SQL/Lesson 9/Slide 8 of 61
  • 9. Implementing Stored Procedures Draft the stored procedure on paper (Contd.) Result: The database in which the stored procedure has to be created is Recruitment The type of procedure is user-defined The name for the stored procedure is prcPrintRecruitmentAgencyList ©NIIT SQL/Lesson 9/Slide 9 of 61
  • 10. Implementing Stored Procedures Create the stored procedure in the database Action: In the Query Analyzer window, type: CREATE PROCEDURE prcPrintRecruitmentAgencyList AS BEGIN PRINT 'List of Recruitment Agencies' SELECT cName, vAddress, cCity, cZip, cPhone, cFax FROM RecruitmentAgencies END Press F5 to execute the statement ©NIIT SQL/Lesson 9/Slide 10 of 61
  • 11. Implementing Stored Procedures Check the existence of the procedure in the database The sp_helptext Command is used to check the existence of a procedure in the database Syntax sp_helptext proc_name Action In the Query Analyzer window, type: sp_helptext prcPrintRecruitmentAgencyList Check the result. The output must be the code that you wrote to create the procedure ©NIIT SQL/Lesson 9/Slide 11 of 61
  • 12. Implementing Stored Procedures Execute the procedure The EXECUTE PROCEDURE statement is used to execute the stored procedure Syntax EXECUTE proc_name or EXEC proc_name or proc_name ©NIIT SQL/Lesson 9/Slide 12 of 61
  • 13. Implementing Stored Procedures Execute the procedure (Contd.) Action: In the Query Analyzer window, type: EXECUTE prcPrintRecruitmentAgencyList or EXEC prcPrintRecruitmentAgencyList or prcPrintRecruitmentAgencyList Press F5 to execute the command ©NIIT SQL/Lesson 9/Slide 13 of 61
  • 14. Implementing Stored Procedures Just a Minute… The query to obtain the list of candidates and their recruitment agencies is: SELECT 'Candidate Name' = vFirstName , 'Recruitment Agency' = cName FROM ExternalCandidate JOIN RecruitmentAgencies ON ExternalCAndidate.cAgencyCode = RecruitmentAgencies.cAgencyCode Create a stored procedure for the same. ©NIIT SQL/Lesson 9/Slide 14 of 61
  • 15. Implementing Stored Procedures 9.D.2 Creating a Generic Stored Procedure Information on contract recruiters in a particular city is required frequently.The city for which details are required changes from time to time. Create a stored procedure that will generate information for a specified city ©NIIT SQL/Lesson 9/Slide 15 of 61
  • 16. Implementing Stored Procedures Task List Identify a method to write a generic procedure that will generate results for variable inputs Draft statements to create a procedure Create the stored procedure in the database Check the existence of the procedure in the database Prepare test cases with existing and non-existing values Execute the procedure with the existing value Execute the procedure with the non-existing value ©NIIT SQL/Lesson 9/Slide 16 of 61
  • 17. Implementing Stored Procedures Identify a method to write a generic procedure that will generate results for variable inputs Parameter A parameter is a placeholder in a query or a stored procedure that accepts a user-defined value whenever the query or stored procedure is executed Types of Parameters Input parameters Output parameters Result: As the city name will be supplied by the user, use input parameters ©NIIT SQL/Lesson 9/Slide 17 of 61
  • 18. Implementing Stored Procedures Draft statements to create a procedure Result: The variable name is @cCity The datatype of the variable is char of size 15. So, the variable needs to be declared, as shown below: @cCity char(15) ©NIIT SQL/Lesson 9/Slide 18 of 61
  • 19. Implementing Stored Procedures Create the stored procedure in the database Action: In the Query Analyzer window, type: CREATE PROC prcListContractRecruiter @cCity char(15) AS BEGIN PRINT 'List of Contract Recruiters' SELECT cName,cCity,cZip,cPhone FROM ContractRecruiter WHERE cCity = @cCity END Press F5 to execute the query ©NIIT SQL/Lesson 9/Slide 19 of 61
  • 20. Implementing Stored Procedures Check the existence of the procedure in the database Action: In the Query Analyzer window, type: sp_helptext prcListContractRecruiter Check the result Prepare test cases with the existing and non-existing values Action: Test for a city, which exists in the ContractRecruiter table: Alexandria Test for a city, which does not exist in the ContractRecruiter table: Boston ©NIIT SQL/Lesson 9/Slide 20 of 61
  • 21. Implementing Stored Procedures Execute the procedure with the existing value Action: In the Query Analyzer window, type: prcListContractRecruiter Alexandria Press F5 to execute the procedure Execute the procedure with the non-existing value Action: In the Query Analyzer window, type: prcListContractRecruiter Boston Press F5 to execute the procedure ©NIIT SQL/Lesson 9/Slide 21 of 61
  • 22. Implementing Stored Procedures 9.D.3 Modifying a Stored Procedure Details of the recruitment agencies for a particular city are required. The city for which the data is required varies from time to time. Instead of creating a new procedure, modify the existing prcPrintRecruitmentAgencyList procedure to meet this requirement. In the new procedure, if no value is passed to the procedure, it should display 'Usage: prcPrintRecruitmentAgencyList city' and stop execution. ©NIIT SQL/Lesson 9/Slide 22 of 61
  • 23. Implementing Stored Procedures Task List Identify a method to modify the existing procedure Draft statements to modify a procedure Verify that the procedure has been modified Execute the procedure ©NIIT SQL/Lesson 9/Slide 23 of 61
  • 24. Implementing Stored Procedures Identify a method to modify the existing procedure The ALTER PROCEDURE Statement is used to modify an existing procedure. The Default Parameter You can use default parameters to pass value to the stored procedure in case no value is passed to it. The value passed as default value must be a constant value or NULL. Result: Use the ALTER PROCEDURE statement to modify the procedure. ©NIIT SQL/Lesson 9/Slide 24 of 61
  • 25. Implementing Stored Procedures Identify a method to modify the existing procedure (Contd.) Use NULL as the default parameter to the procedure. If no value is passed to the procedure parameter, the parameter would contain a NULL value. If the value of the parameter is NULL, the procedure should display a message explaining the usage of the procedure. Draft statements to modify a procedure Action: In the Query Analyzer window, type: ALTER PROCEDURE prcPrintRecruitmentAgencyList @city char(15)=NULL ©NIIT SQL/Lesson 9/Slide 25 of 61
  • 26. Implementing Stored Procedures Draft statements to modify a procedure (Contd.) AS BEGIN IF @city is null BEGIN PRINT 'Usage: prcPrintRecruitmentAgencyList city' RETURN END PRINT 'List of Recruitment Agencies' SELECT cName,vAddress,cZip,cPhone FROM RecruitmentAgencies WHERE cCity = @city ©NIIT END SQL/Lesson 9/Slide 26 of 61
  • 27. Implementing Stored Procedures Draft statements to modify a procedure (Contd.) Press F5 to execute the query In the above code, the RETURN statement passes the control back to the position from where it was called ©NIIT SQL/Lesson 9/Slide 27 of 61
  • 28. Implementing Stored Procedures Verify that the procedure has been modified Action: In the Query Analyzer window, type: sp_helptext prcPrintrecruitmentAgencyList Press F5 to execute the query Execute the procedure Action: In the Query Analyzer window, type: EXEC prcPrintRecruitmentAgencyList Alexandria Press F5 to execute the query ©NIIT SQL/Lesson 9/Slide 28 of 61
  • 29. Implementing Stored Procedures Execute the procedure (Contd.) In case you do not pass any parameter to the procedure by typing: prcPrintRecruitmentAgencyList you will get the following output: Usage: prcPrintRecruitmentAgencyList city ©NIIT SQL/Lesson 9/Slide 29 of 61
  • 30. Implementing Stored Procedures 9.D.4 Notifying Successful Execution Modify the prcPrintRecruitmentAgencyList procedure to notify users of its successful execution ©NIIT SQL/Lesson 9/Slide 30 of 61
  • 31. Implementing Stored Procedures Task List Identify a method to write a procedure that will return a value Draft the procedure Modify the procedure in the database Check that the procedure has been modified in the database Execute the procedure ©NIIT SQL/Lesson 9/Slide 31 of 61
  • 32. Implementing Stored Procedures Identify a method to write a procedure that will return a value The RETURN Keyword You use the RETURN statement to return values from a stored procedure Syntax RETURN value Result: The RETURN statement can be used to return values from a stored procedure ©NIIT SQL/Lesson 9/Slide 32 of 61
  • 33. Implementing Stored Procedures Draft the procedure Result: The batch statements for creating the stored procedure are as follows: ALTER PROCEDURE prcPrintRecruitmentAgencyList @city char(15) AS BEGIN IF EXISTS(SELECT * FROM RecruitmentAgencies WHERE cCity=@city) ©NIIT SQL/Lesson 9/Slide 33 of 61
  • 34. Implementing Stored Procedures Draft the procedure (Contd.) BEGIN PRINT 'List of Recruitment Agencies' SELECT cName,vAddress,cZip,cPhone FROM RecruitmentAgencies WHERE cCity = @city Return 0 END ELSE BEGIN PRINT 'No Records Found for given city' RETURN 1 END END ©NIIT SQL/Lesson 9/Slide 34 of 61
  • 35. Implementing Stored Procedures Modify the procedure in the database Action: In the Query Analyzer window, type prcPrintRecruitmentAgencyList Press F5 to execute the statement ©NIIT SQL/Lesson 9/Slide 35 of 61
  • 36. Implementing Stored Procedures Check that the procedure has been modified in the database Action: In the Query Analyzer window, type: sp_helptext prcPrintRecruitmentAgencyList Press F5 to execute the statement ©NIIT SQL/Lesson 9/Slide 36 of 61
  • 37. Implementing Stored Procedures Execute the procedure Action: In the Query Analyzer window, type: DECLARE @ReturnValue int EXEC @ReturnValue = prcPrintRecruitmentAgencyList 'Alexandria' SELECT @ReturnValue Press F5 to execute the statement. When the above statements are executed, the value returned by the procedure prcPrintRecruitmentAgencyList would be stored in the variable @ReturnValue. This value would be displayed by the SELECT statement ©NIIT SQL/Lesson 9/Slide 37 of 61
  • 38. Implementing Stored Procedures 9.D.5 Calling One Procedure From Another Details about the recruitment agencies and the contract recruiters in a city are required in a single report. Create a single procedure that uses the existing procedures for the report ©NIIT SQL/Lesson 9/Slide 38 of 61
  • 39. Implementing Stored Procedures Task List Identify a method to modify the existing procedure Create the procedure in the database Check the existence of the procedure in the database Execute the procedure with parameters ©NIIT SQL/Lesson 9/Slide 39 of 61
  • 40. Implementing Stored Procedures Identify a method to write a procedure that will use an existing procedure Nested Procedures You can execute or call one procedure from within another procedure Result: Create a new stored procedure that will call the existing procedures ©NIIT SQL/Lesson 9/Slide 40 of 61
  • 41. Implementing Stored Procedures Create the procedure in the database Action: In the Query Analyzer window, type: CREATE PROCEDURE prcDisplayBoth @city char(15) AS BEGIN EXEC prcListContractRecruiter @city EXEC prcPrintRecruitmentAgencyList @city END Press F5 to execute the statement ©NIIT SQL/Lesson 9/Slide 41 of 61
  • 42. Implementing Stored Procedures Check the existence of the procedure in the database Action: In the Query Analyzer window, type: sp_helptext prcDisplayBoth Press F5 to execute the statement Execute the procedure with parameters Action: In the Query Analyzer window, type: prcDisplayBoth 'Alexandria' Press F5 to execute the statement ©NIIT SQL/Lesson 9/Slide 42 of 61
  • 43. Implementing Stored Procedures Just a Minute… You need to modify a stored procedure. Which command will you use to modify the procedure? ©NIIT SQL/Lesson 9/Slide 43 of 61
  • 44. Implementing Stored Procedures 9.D.6 Returning Multiple Output Values A formatted report of the status of positions available in the company is to be displayed. Create a procedure, prcGetPositionDetail which will return the position description, the budgeted manpower and the current strength of employees for a given position. Create another procedure called prcDisplayPositionStatus that will display cRequisitionCode, vRegion, and siNoOfVacancy from the Requisition table. The procedure prcDisplayPositionStatus should also call the prcGetPositionDetail procedure and display the values returned by it for position '0002' in the following format: ©NIIT SQL/Lesson 9/Slide 44 of 61
  • 45. Implementing Stored Procedures 9.D.6 Returning Multiple Output Values (Contd.) The Status for the Position: Maketing Manager Budgeted Strength : 100 Current Strength : 83 cRequisitionCode vRegion siNoOfVacancy ---------------- -------------------- ---------- 000002 Texas 11 ©NIIT SQL/Lesson 9/Slide 45 of 61
  • 46. Implementing Stored Procedures Task List Identify a method to write a generic procedure that will return more than one value Create the procedure in the database Check whether the procedure exists in the database Execute the procedure with parameters ©NIIT SQL/Lesson 9/Slide 46 of 61
  • 47. Implementing Stored Procedures Identify a method to write a generic procedure that will return more than one value The OUTPUT Parameter - is used to return more than one value from the procedure Syntax CREATE PROC[EDURE] procedure_name [ {@parameter data_type} [OUTPUT] ] AS sql_statement [...n] Result: ® Use CREATE PROCEDURE with the OUTPUT option ©NIIT SQL/Lesson 9/Slide 47 of 61
  • 48. Implementing Stored Procedures Create the procedure in the database Action: In the Query Analyzer Window, type the statements given below. CREATE PROCEDURE prcGetPositionDetail @Pcode char(4), @Description char(30) OUTPUT, @budget int OUTPUT, @CurrentStrength int OUTPUT AS BEGIN IF EXISTS(SELECT * FROM Position WHERE cPositionCode = @PCode) ©NIIT SQL/Lesson 9/Slide 48 of 61
  • 49. Implementing Stored Procedures Create the procedure in the database (Contd.) BEGIN SELECT @Description = vDescription,@budget = iBudgetedStrength, @CurrentStrength = iCurrentStrength FROM Position WHERE cPositionCode=@Pcode RETURN 0 END ELSE RETURN 1 END Press F5 to execute ©NIIT SQL/Lesson 9/Slide 49 of 61
  • 50. Implementing Stored Procedures Create the procedure in the database (Contd.) In the Query Analyzer Window, type: CREATE PROCEDURE prcDisplayPositionStatus @PCode char(4) AS BEGIN DECLARE @Description char(30) DECLARE @budget int DECLARE @CurrentStrength int DECLARE @ReturnValue int EXEC @ReturnValue = prcGetPositionDetail @Pcode, @Description output, @Budget output, @CurrentStrength output ©NIIT SQL/Lesson 9/Slide 50 of 61
  • 51. Implementing Stored Procedures Create the procedure in the database (Contd.) IF (@ReturnValue = 0) BEGIN PRINT 'The Status for the Position: ' + @Description PRINT 'Budgeted Strength : ' + CONVERT( char(30), @budget) PRINT 'Current Strength : ' + CONVERT (char(30), @CurrentStrength) SELECT cRequisitionCode,vRegion, siNoOfVacancy FROM Requisition WHERE cPositionCode=@Pcode ©NIIT SQL/Lesson 9/Slide 51 of 61
  • 52. Implementing Stored Procedures Create the procedure in the database (Contd.) END ELSE PRINT 'No records for the given position code' END Press F5 to execute ©NIIT SQL/Lesson 9/Slide 52 of 61
  • 53. Implementing Stored Procedures Check whether the procedure exists in the database In the Query Analyzer window, type and execute the following statements: sp_helptext prcGetPositionDetail go sp_helptext prcDisplayPositionStatus go ©NIIT SQL/Lesson 9/Slide 53 of 61
  • 54. Implementing Stored Procedures Execute the procedure with parameters Action: In the Query Analyzer window, type: prcDisplayPositionstatus '0002' Press F5 to execute Verify that the required output is displayed ©NIIT SQL/Lesson 9/Slide 54 of 61
  • 55. Implementing Stored Procedures The RECOMPILE Option To generate an updated execution plan, you must recompile the stored procedure, each time you execute the stored procedure Syntax CREATE PROCEDURE proc_name [WITH RECOMPILE] AS sql_statements ©NIIT SQL/Lesson 9/Slide 55 of 61
  • 56. Implementing Stored Procedures The DROP PROCEDURE Statement Is used to drop a stored procedure from the database Syntax DROP PROCEDURE proc_name You cannot retrieve a procedure once it is dropped ©NIIT SQL/Lesson 9/Slide 56 of 61
  • 57. Implementing Stored Procedures Extended Stored Procedures Allow you to create your own external routines in a programming language such as C Are Dynamic-Link Libraries (DLLs) that SQL Server can dynamically load and execute ©NIIT SQL/Lesson 9/Slide 57 of 61
  • 58. Implementing Stored Procedures Summary In this lesson, you learned that: A stored procedure is a collection of various T-SQL statements that are stored under one name and executed as a single unit A stored procedure can be created either in the Enterprise Manager or in the Query Analyzer window with 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 network congestion ©NIIT SQL/Lesson 9/Slide 58 of 61
  • 59. Implementing Stored Procedures Summary (Contd.) The various types of stored procedures are: User-defined System Temporary Remote Extended A stored procedure accepts and returns data through the following: Input parameters ©NIIT SQL/Lesson 9/Slide 59 of 61
  • 60. Implementing Stored Procedures Summary (Contd.) Output parameters Return statements A stored procedure can be executed using the EXECUTE statement A stored procedure can be altered using the ALTER PROCEDURE statement A stored procedure can be viewed using the sp_help and the sp_helptext system procedures To generate an updated execution plan, you must recompile the stored procedure each time you execute the stored procedure ©NIIT SQL/Lesson 9/Slide 60 of 61
  • 61. Implementing Stored Procedures Summary (Contd.) To recompile a stored procedure automatically, you must create the stored procedure with a WITH RECOMPILE option A stored procedure can be dropped using the DROP PROCEDURE statement Extended stored procedures are Dynamic-Link Libraries (DLLs) that SQL Server can dynamically load and execute ©NIIT SQL/Lesson 9/Slide 61 of 61