Você está na página 1de 16

Using stored procedures

to query
SQL Server databases

Procedure definition:
CREATE Procedure PROCEDURE_NAME
@PARAMETER_NAME DATA_TYPE = DefaultValue
AS
SQL_commands

Procedure call/execution:
If no value is explicitly specified for the input parameter when
the procedure is executed then the default value will be used.
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

Optional parameters in procedures Examples:


Procedure definition:

Procedure execution:

General rules:
Parameters must be separated by commas ( , );
Optional parameters (with specified default values)
may be mixed with the mandatory ones (with no
default values);
At execution time, parameter order is relevant only in
cases when values alone are specified while parameter
names are left out;
When optional parameters (with default values)
precede the mandatory ones, in order to use their
default values all other parameters (required) must be
specified according to the syntax:
@ParameterName = Value

Multiple parameters in procedures Examples:


Procedure definition:

Procedure execution:

The alternative structure: IF ELSE


IF CONDITION_Statement
BEGIN
SQL_Commands
END
[ ELSE
BEGIN
SQL_Commands
END ]

The repetitive structure: WHILE


WHILE CONDITION_Statement
BEGIN
SQL_Commands
BREAK
SQL_Commands
END

BREAK causes an immediate exit from the loop; execution continues


with the first line of code which follows after END
DECLARE @v int=1
WHILE @v<4
BEGIN
Print current value of variable v: + convert(char(1),@v)
Set @v=@v+1
END

A transaction consists of a single instruction


or an assembly of instructions acting as a
single processing unit: either all operations
are executed or none is, thus ensuring data
coherence.
Purpose: transactions should
actions leading to data errors.

prevent

Operations belonging to the same


transaction cannot be partly executed:
if one of them fails than all operations
are canceled.

Ending transactions:
by Committing when all constituent
operations were successfully performed -> their
consequences finally become apparent in the
database.
by Rolling Back when all constituent
operations are canceled due to an exception or a
specified constraint and the database reverts to
the same state that preceded transaction
execution.

Transactions are mainly used for update actions


performed by stored procedures;
To check whether previously executed
statements resulted in errors, @@Error system
function can be used in logical tests controlling
alternative structures;
To get the value generated for autonumber
(identity) fields, Scope_Identity() system
function should be used.

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


records affected by the previously executed query

@@TRANCOUNT - system function -> returns the number

of uncommitted transactions for the current connection


@@ERROR - system function -> Returns the error number

for the previously executed SQL statement


ROLLBACK TRANSACTION | COMMIT TRANSACTION > end
transactions by canceling / committing

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


Parameters:
1: User-defined error message
2: Number 0 - 25 (<17 for user-defined errors; >19 for fatal errors)
3: Number 0 - 255 used when debugging SQL code

Transactions in procedures Example:


Stored
procedure to
remove a
certain
examination
and transfer
associated
marks (if
any) to
another
existing
examination:

Transactions in procedures Example:


Stored procedure
to remove a
certain exam and
transfer
associated marks
(if any) to a new
exam that must
be generated by
the system:
Prerequisites:
1. The primary key
in Exam table
(ExamId) is an
identity field
(autonumber)
2. Cascade delete
enabled for
relationships
involving Exam
as parent table

BEGIN TRY
SQL-commands
END TRY
BEGIN CATCH
Code executed when errors occur (messages to display etc.)
END CATCH

Useful functions :
ERROR_NUMBER() returns the error number
ERROR_LINE() returns the number of the code line
where the error has occurred
ERROR_SEVERITY returns a number smaller than 25
corresponding to error severity
ERROR_MESSAGE() returns the message describing
the error

BEGIN TRY
BEGIN 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 database
END TRY
BEGIN CATCH
-- Error messages may be displayed here
-- the uncommitted transaction is canceled:
IF @@TRANCOUNT > 0 ROLLBACK
END CATCH

Você também pode gostar