2014_Course 7.A

Embed Size (px)

Citation preview

  • 8/10/2019 2014_Course 7.A

    1/16

    Using stored procedures

    to querySQL Server databases

  • 8/10/2019 2014_Course 7.A

    2/16

    CREATE Procedure

    PROCEDURE_NAME

    @PARAMETER_NAME DATA_TYPE

    =

    DefaultValue

    AS

    SQL

    _commands

    Procedure definition:

    Procedure call/execution:

    Option 1: Providing the parameter value

    Exec

    PROCEDURE_NAME

    Parameter_Value

    Option

    2:

    Parameter left out

    -

    > the implicit value is used

    Exec

    PROCEDURE_NAME

    Exec

    PROCEDURE_NAME

    default

    If no value is explicitly specified for the input parameter when

    the procedure is executed then the default value will be used.

  • 8/10/2019 2014_Course 7.A

    3/16

    Optional parameters in proceduresExamples:

    Procedure definition:

    Procedure execution:

  • 8/10/2019 2014_Course 7.A

    4/16

    General rules:

    Parameters must be separated by commas ( , );

    Optional parameters (with specified default values)may be mixed with the mandatory ones (with nodefault values);

    At execution time, parameter order is relevant only incases when values alone are specified while parameternames are left out;

    When optional parameters (with default values)precede the mandatory ones, in order to use theirdefault values all other parameters (required) must bespecified according to the syntax:

    @ParameterName = Value

  • 8/10/2019 2014_Course 7.A

    5/16

    Multiple parameters in proceduresExamples:

    Procedure definition:

    Procedure execution:

  • 8/10/2019 2014_Course 7.A

    6/16

    The alternative structure: IF ELSEIF

    CONDITION_Statement

    BEGIN

    SQL

    _Commands

    END

    [

    ELSE

    BEGIN

    SQL

    _Commands

    END

    ]

  • 8/10/2019 2014_Course 7.A

    7/16

    The repetitive structure: WHILE

    WHILECONDITION_StatementBEGIN

    SQL_Commands

    BREAK

    SQL_Commands

    END

    BREAKcauses an immediate exit from the loop; execution continueswith the first line of code which follows after END

    DECLARE @v int=1

    WHILE@v

  • 8/10/2019 2014_Course 7.A

    8/16

    A transaction consists of a single instructionor an assembly of instructions acting as asingle processing unit: either all operationsare executed or none is, thus ensuring data

    coherence.Purpose: transactions should preventactions leading to data errors.

    Operations belonging to the sametransaction cannot be partly executed:if one of them fails than all operationsare canceled.

  • 8/10/2019 2014_Course 7.A

    9/16

    Ending transactions:by Committing when all constituentoperations were successfully performed -> theirconsequences finally become apparent in thedatabase.

    by Rolling Back when all constituentoperations are canceled due to an exception or a

    specified constraint and the database reverts tothe same state that preceded transactionexecution.

  • 8/10/2019 2014_Course 7.A

    10/16

    Transactions are mainly used for update actionsperformed by stored procedures;

    To check whether previously executed

    statements resulted in errors, @@Errorsystemfunction can be used in logical tests controllingalternative structures;

    To get the value generated for autonumber(identity) fields, Scope_Identity() systemfunction should be used.

  • 8/10/2019 2014_Course 7.A

    11/16

    @@ROWCOUNT - system function -> returns the number of

    records affected by the previously executed query

    @@TRANCOUNT - system function -> returns the numberof uncommitted transactions for the current connection

    @@ERROR - system function -> Returns the error numberfor the previously executed SQL statement

    ROLLBACK TRANSACTION | COMMIT TRANSACTION> endtransactions by canceling /committing

    RAISERROR(message to display, severity level, identification code)

    Parameters:

    1: User-defined error message

    2: Number 0 - 25 (19 for fatal errors)3: Number 0 - 255 used when debu in SQL code

    T i i d E l

  • 8/10/2019 2014_Course 7.A

    12/16

    Stored

    procedure to

    remove a

    certain

    examination

    and transfer

    associated

    marks (if

    any) to

    anotherexisting

    examination:

    Transactions in proceduresExample:

    T E

  • 8/10/2019 2014_Course 7.A

    13/16

    Stored procedure

    to remove a

    certain exam and

    transferassociated marks

    (if any) to a new

    exam that must

    be generated by

    the system:

    Prerequisites:1. The primary key

    in Examtable

    (ExamId) is an

    identity field(autonumber)

    2. Cascade delete

    enabled for

    relationships

    involving Exam

    as parent table

    Transact ons n proce uresExamp e:

  • 8/10/2019 2014_Course 7.A

    14/16

    Useful functions :

    ERROR_NUMBER()returns the error number

    ERROR_LINE()returns the number of the code line

    where the error has occurredERROR_SEVERITYreturns a number smaller than 25corresponding to error severity

    ERROR_MESSAGE()returns the message describing

    the error

    BEGIN TRY

    SQL-commands

    END TRY

    BEGIN CATCH

    Code executed when errors occur (messages to display etc.)

    END CATCH

  • 8/10/2019 2014_Course 7.A

    15/16

  • 8/10/2019 2014_Course 7.A

    16/16

    BEGIN TRYBEGIN TRANSACTION -- a transaction is started

    -- INSERT, UPDATE, DELETE statements follow:

    -- If preceding commands were successful:COMMIT -- the transaction is completed

    -- results are saved to the databaseEND TRY

    BEGIN CATCH-- Error messages may be displayed here

    -- the uncommitted transaction is canceled:

    IF @@TRANCOUNT > 0 ROLLBACKEND CATCH