Session6_SP_UDF

Embed Size (px)

Citation preview

  • 8/7/2019 Session6_SP_UDF

    1/42

    Stored Procedures &

    User-Defined Functions

    Vu Tuyet [email protected]

    Hanoi University of Technology

    1

  • 8/7/2019 Session6_SP_UDF

    2/42

    Microsoft

    Microsoft

    Introduction to SQL Batch Processing

    Batch

    Individual SQL

    commands

    Grouped to form abatch

    Compiledas singleexecutionplan

  • 8/7/2019 Session6_SP_UDF

    3/42

    Microsoft

    Microsoft

    Example

    Use Pubs

    Select * from authorsUpdate authors

    set phone= '890 451-7366

    where au_lname= 'White'

    Go

  • 8/7/2019 Session6_SP_UDF

    4/42

    Microsoft

    Microsoft

    Outline

    Understanding the concepts of batch and batchprocessing

    T-SQL Programming Define and assign variables

    Cursors for data retrieval

    Control statements

    Write SQL statements using SQL Server basic functions

    Use basic functions in a query

    Implementing Stored Procedures

    Implementing User-Defined Functions

    4

  • 8/7/2019 Session6_SP_UDF

    5/42

    Microsoft

    Microsoft

    Assigning values to variables

    SET statement

    SET @local_variable name = value

    SELECT statementSELECT @local_variable name = value

    Ex

    ampleSET @CUST=FRANK

    SELECT CUSTOMERID,COMPANYNAME

    FROM CUSTOMERS

    WHERE CUSTOMERID = @CUST

  • 8/7/2019 Session6_SP_UDF

    6/42

    Microsoft

    Microsoft

    Variables

    SQL Server supports two types of variables in T-SQL

    @@global_variable

    @local_variable

  • 8/7/2019 Session6_SP_UDF

    7/42

    MicrosoftMicrosoft

    List of Global variables

    @@CONNECTIONS Number of connections made to the server

    since it was last started.

    @@CPU_BUSY Number of milliseconds the system has been

    processing since SQL Server was started

    @@CURSOR_ROWS Number of rows in the most recently opened

    cursor.

    @@ERROR Error number of the last T-SQL error

    @@FETCH_STATUS 0 if the last fetch status was successful.

    -1 if there was an error

  • 8/7/2019 Session6_SP_UDF

    8/42

  • 8/7/2019 Session6_SP_UDF

    9/42

    MicrosoftMicrosoft

    Cursors to Retrieve Data

    Allowing positioning at specific rows of the result set

    Retrieving one row or block of rows from the current

    position in the result set

    Supporting data modifications to the rows at the current

    position in the result set

    Supporting different levels of visibility for changes made

    by other users to the data in the result set

    Providing access to the data in a result set for T-SQL

    statements in scripts, stored procedures, and triggers

  • 8/7/2019 Session6_SP_UDF

    10/42

    MicrosoftMicrosoft

    CursorImplementations

    Transact-SQL Server Cursors

    Used in scripts, stored procedures, and triggers

    Implemented on the server

    API Server Cursors

    Implemented on the server but managed by API cursor

    functions (OLE DB, ODBC, DB-Library)

    Client Cursors Entire result set is cached on client and all cursor

    operations are performed against this cached set

  • 8/7/2019 Session6_SP_UDF

    11/42

    MicrosoftMicrosoft

    Working with T-SQL Server Cursors

    Declare the cursor

    Populate the cursor

    Retrieve (fetch) the result set

    First, Next, Prior, Last, Absolute n, Relative n Optional: update or delete a row

    Close the cursor

    Free resources allocated to the cursor

  • 8/7/2019 Session6_SP_UDF

    12/42

  • 8/7/2019 Session6_SP_UDF

    13/42

    MicrosoftMicrosoft

    Control Statements Contd

  • 8/7/2019 Session6_SP_UDF

    14/42

    MicrosoftMicrosoft

    BEGIN..END

    A set of TSQL statements to be executed can be enclosedin BEGIN..END.

    Syntax:

    BEGIN

    { statement | statement_block}

    END

  • 8/7/2019 Session6_SP_UDF

    15/42

    MicrosoftMicrosoft

    IF..ELSE

    We can execute different

    sets of SQL statements based on

    specified conditions.

    Syntax:IF Boolean_expression

    { sql_statement | statement_block}

    [ ELSE{ sql_statement |

    statement_block } ]

  • 8/7/2019 Session6_SP_UDF

    16/42

    MicrosoftMicrosoft

    Example

  • 8/7/2019 Session6_SP_UDF

    17/42

    MicrosoftMicrosoft

    WHILE construct

    We can execute a SQL statement or a

    block of statements based on some condition.

    Syntax:

    WHILE Boolean_expression

    { statement | statement_block}

    [ BREAK ]

    { statement | statement_block

    }

    [ CONTINUE ]

  • 8/7/2019 Session6_SP_UDF

    18/42

    MicrosoftMicrosoft

    Example

    USE pubsGOWHILE (SELECT AVG(price) FROM titles) < $30BEGIN

    UPDATE titlesSET price = price * 2

    SELECT MAX(price) FROM titlesIF (SELECT MAX(price) FROM titles) > $50

    BREAK

    ELSECONTINUE

    ENDPRINT 'Too much for the market to bear'

  • 8/7/2019 Session6_SP_UDF

    19/42

    MicrosoftMicrosoft

    GOTO keyword

    GOTO:

    We can change the flow of execution to a specified location (label).The statements after GOTO keyword are skipped and the

    execution process continues at the specified label in the GOTOstatement.

    Syntax:

    GOTO label

  • 8/7/2019 Session6_SP_UDF

    20/42

    MicrosoftMicrosoft

    RETURN

    RETURN: We can use RETURN at any point to exit from a block,procedure. Statements after the RETURN statement are notexecuted.

    Syntax:

    RETURN [ integer_expression ]

  • 8/7/2019 Session6_SP_UDF

    21/42

    MicrosoftMicrosoft

    CASE statement

    Allowing to return a value based on whether anexpression is true.

    Can be used wherever an expression is allowed.

    Syntax:CASE expression

    WHEN expression1 THEN expression1[[WHEN expression2 THEN expression2] []][ELSE expression]

    END

    Ex

    ample:SELECT au_fname, au_lname,CASE state

    WHEN 'OR' THEN 'Oregon'

    END AS StateName FROMauthors

  • 8/7/2019 Session6_SP_UDF

    22/42

    MicrosoftMicrosoft

    Multi column updates using CASE

    UPDATE publishersSET state =CASE

    WHEN country "USA"THEN "--"

    ELSE stateEND,city =CASE

    WHEN pub_id = "9999"THEN "LYON"ELSE city

    ENDWHERE country "USA" ORpub_id = "9999"

    Two or more

    columns canbe updatedusing onecommand inthis manner

  • 8/7/2019 Session6_SP_UDF

    23/42

    MicrosoftMicrosoft

    Math Functions

    AVG()

    MIN()

    MAX() SUM()

    COUNT()

    SQUARE()

    SQRT()

    ROUND()

  • 8/7/2019 Session6_SP_UDF

    24/42

    MicrosoftMicrosoft

    String Functions

    ASCII()

    CHAR()

    UPPE

    R() LOWER()

    LEN()

    LTRIM()

    RTRIM()

    LEFT()

    RIGHT()

  • 8/7/2019 Session6_SP_UDF

    25/42

    MicrosoftMicrosoft

    Time Functions

    GETDATE()

    DATEPART(YY,getdate())

    DATEDIFF(X,Y,Z) DAY()

    MONTH()

    YEAR()

  • 8/7/2019 Session6_SP_UDF

    26/42

    MicrosoftMicrosoft

    System Functions

    DB_ID([database_name])

    DB_NAME([database_id])

    HOST_ID()

    HOST_NAME() ISNULL(expr,value)

    OBJECT_ID(obj_name)

    OBJECT_NAME(object_id)

    SUSE

    R_SID([login_name])

    SUSER_ID([login_name])

    SUSER_SNAME([server_user_id])

    SUSER_NAME([server_user_id])

    USER_ID([user_name])

    USER_NAME([user_id])

  • 8/7/2019 Session6_SP_UDF

    27/42

    MicrosoftMicrosoft

    Outline

    Understanding the concepts of batch and batchprocessing

    T-SQL Programming Define and assign variables

    Cursors for data retrieval

    Control statements

    Write SQL statements using SQL Server basic functions

    Use basic functions in a query

    Implementing Stored Procedures

    Implementing User-Defined Functions

    27

  • 8/7/2019 Session6_SP_UDF

    28/42

  • 8/7/2019 Session6_SP_UDF

    29/42

  • 8/7/2019 Session6_SP_UDF

    30/42

    MicrosoftMicrosoft

    Modifying a Stored Procedure

    ALTER PROCEDURE GetSubjectsASSELECT *FROM dbo.Subject;

  • 8/7/2019 Session6_SP_UDF

    31/42

    MicrosoftMicrosoft

    Deleting a Stored Procedure

    DROP PROCEDURE dbo.GetSubjects

  • 8/7/2019 Session6_SP_UDF

    32/42

    MicrosoftMicrosoft

    Executing a Stored Procedure

    Local stored procedures

    Execute

    Remote stored procedures

    Execute

    or

    OpenQuery(linked server name,exec stored procedure)

    Example

    Execute dbo.GetSubjects

  • 8/7/2019 Session6_SP_UDF

    33/42

    MicrosoftMicrosoft

    Outline

    Understanding the concepts of batch and batchprocessing

    T-SQL Programming Define and assign variables

    Cursors for data retrieval

    Control statements

    Write SQL statements using SQL Server basic functions

    Use basic functions in a query

    Implementing Stored Procedures

    Implementing User-Defined Functions

    33

  • 8/7/2019 Session6_SP_UDF

    34/42

    MicrosoftMicrosoft

    User-Defined Function

    A function returning value

    Advantages:

    better performance, higher productivity, ease of use, increasedscalability for database application

    embed complex logic within a query.

    create new functions for complex expressions.

    Three distinct types

    Scalar functions that return a single value Updateable inline table functions similar to views

    Multi-statement table functions that build a result set with code

  • 8/7/2019 Session6_SP_UDF

    35/42

    MicrosoftMicrosoft

    Creating a Scalar Function

  • 8/7/2019 Session6_SP_UDF

    36/42

    MicrosoftMicrosoft

    Creating a Inline Table Function

  • 8/7/2019 Session6_SP_UDF

    37/42

  • 8/7/2019 Session6_SP_UDF

    38/42

    MicrosoftMicrosoft

    Modifying a Scalar Function

  • 8/7/2019 Session6_SP_UDF

    39/42

  • 8/7/2019 Session6_SP_UDF

    40/42

  • 8/7/2019 Session6_SP_UDF

    41/42

    MicrosoftMicrosoft

    Summary

    41

  • 8/7/2019 Session6_SP_UDF

    42/42

    MicrosoftMicrosoft