Using Stored Procedures To Query SQL Server Databases
Using Stored Procedures To Query SQL Server Databases
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
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
Procedure execution:
prevent
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.
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: