Handout 7 - Stored Procedures, Transactions and SQL Programming
Handout 7 - Stored Procedures, Transactions and SQL Programming
doc
Haramaya University
College of computing and Informatics
RECOMMENDED TEXTS:
1 Overview
This handout describes SQL stored procedures and transactions. It also looks at some of the
T-SQL programming statements that can be used in stored procedures.
2 Stored Procedures
A SQL stored procedure is a saved piece of programming code, written in SQL, that can
accept passed parameters and be used to accomplish complex tasks. A stored procedure can
also return values to the calling program – which can be SQL or another application.
Transact-SQL provides programming statements that can be used to control the flow of the
program, and also provides functions (such as the date time functions we looked at in handout
6) for manipulating data values.
A stored procedure can be simply used just to save a select, update, insert or delete query as
well as to carry out more complex tasks. Because a procedure can accept parameters, they are
often used to save a select query when the search condition in the where clause is based on a
variable value e.g. ion the Pubs database, a query to get all the titles of a given type. The type
can be passed as a parameter.
Stored procedures are beneficial because they are pre-compiled – this means that the DBMS
builds an execution plan for the code when it is saved. Normally, the DBMS needs to build
an execution plan for a query when it is executed. Having a pre-compiled plan speeds up the
execution.
Page 1 of 9
CCI – Computer Science Dept 655445336.doc
AS
Sql_statement […n]
Notes:
The keyword PROC or PROCEDURE can be used
A parameter is a value that can be passed into a procedure. Each parameter is given a
name, which must begin with the @ sign. A parameter can also be assigned a default
value by putting '= default_value' after the parameter, where default_value is the
desired default value. This means that the procedure can be executed without
supplying a value for the parameter, and the default value will be used instead. The
default value must be a constant value or NULL.
The data type must be specified for each parameter.
A parameter can also be specified as an OUTPUT. This means that the value of the
parameter can be set during the procedure, and it is available to the calling code.
A procedure can have up to 2100 parameters.
Sql_statement is any number of SQL statements to be run when the procedure is
executed. This can include executing one or more other stored procedures.
For example – the procedure 'byroyalty' is defined in the Pubs database. It is used to get a list
of Author IDs for authors who have a specified royalty percentage. The royalty percentage is
supplied as a parameter. Note that the GO statement is always the last line in a stored
procedure CREATE statement. It is placed at the end of the batch of SQL statements – this is
to tell the SQL Server to execute the statements in the procedure.
GO
The data type for a parameter should be consistent with the use of the parameter. For
example, the titleauthor.royaltyper column has data type int, so the parameter should also be
of int data type.
If this is executed, it will drop the procedure named 'sp_CreateNewTitle'. If the procedure
does not exist in the database, a message indicating this will be returned.
If you wish to make a change to a procedure, it has to be dropped and then re-created with the
change in it.
Page 2 of 9
CCI – Computer Science Dept 655445336.doc
EXECUTE byroyalty 30
This will execute the byroyalty stored procedure, passing 30 as the value for the @percentage
parameter.
If the statement to execute a procedure is the first line in a batch, then the EXECUTE can be
omitted e.g.
byroyalty 30
but
select au_id, au_fname, au_lname from authors
byroyalty 30
- this will return an error because the execution of the procedure is the second line in the
batch. This should be:
select au_id, au_fname, au_lname from authors
execute byroyalty 30
To see the definition for a stored procedure, double-click on it. This brings up the Stored
Procedure Properties dialog.
In this window, you can see the SQL that creates the procedure, including the Create
Procedure statement.
To modify the SQL statements executed by the procedure, edit the SQL here.
Click the Check Syntax button after making a change – if there are any errors in the
SQL, they will be reported when the button is clicked.
Click Apply to apply the changes to the procedure – after applying, you can switch to
the Query Analyzer to execute it and make sure the results are as you expect.
Click OK to apply the changes to the procedure and to exit from the dialog.
Click the Check Syntax button – if there are syntax errors in the SQL, they will be
reported
When finished writing the procedure, click OK to save it
To drop a stored procedure in Enterprise Manager, navigate to the Stored Procedure list in the
database.
Click on the stored procedure to be dropped, and hit the Delete key or right-click and
choose Delete.
This will bring up the Drop Objects dialog.
To see if there are any objects dependent on the procedure and what objects it is
dependent on, click the Show Dependencies button.
Make sure that only the procedure you want to drop is listed, then click Drop All to
drop it.
If there are any objects that depend on the procedure e.g. another stored procedure
that references it, the procedure cannot be dropped until those objects are dropped.
SQL Server will warn if this is the case and will not drop the procedure.
3 An Overview of Transactions
A logical unit of work must exhibit 4 properties to qualify as a transaction. These are known
as the ACID properties of a transaction – this is an acronym for Atomicity, Consistency,
Isolation and Durability. Each of these properties is explained below.
Atomicity – a transaction must be an atomic piece of work – this means that either all of its
data modifications are performed or none of them is performed. SQL Server provides
mechanisms to commit transactions that have completed successfully and to roll back
transactions when some part fails.
Consistency – when completed, a transaction must leave all data in a consistent state. In a
relational database, all rules must be applied to the transaction's modifications to maintain all
data integrity – the rules include referential integrity (foreign key constraints), nullability and
check constraints.
Page 4 of 9
CCI – Computer Science Dept 655445336.doc
Durability – after a transaction has completed, its effects are permanent in the system. The
modifications should persist even in the event of a system failure. SQL Server provides a way
of logging all transactions so that if hardware or software fails, the transaction logs can be
used to restore the system to the state it was in at the point of failure.
SQL provides a series of statements for explicitly beginning and ending transactions.
Some DBMS applications, including SQL Server, also do implicit transactions for certain
SQL statements – this means that it is implied that a transaction has started when these
statements are executed. The statements include ALTER, CREATE, DELETE, DROP,
INSERT, SELECT and UPDATE.
Statement Description
BEGIN TRAN[SACTION] Marks the starting point of an explicit transaction
COMMIT TRAN[SACTION] Marks the end of an explicit or implicit transaction. An explicit transaction
is started with BEGIN TRANSACTION; an implicit transaction is started
by the DBMS when any of the statements indicated above are executed.
ROLLBACK TRAN[SACTION] Rolls back an implicit or explicit transaction to the starting point – the
starting point is the BEGIN TRANSACTION statement for an explicit
transaction or the first statement for an implicit transaction.
A roll back undoes or erases any data modifications made since the
transaction was started.
A transaction cannot be rolled back after a COMMIT TRANSACTION has
been executed.
Autocommit Transactions
This is the default mode. It means that every individual SQL statement is treated as a
transaction. If the execution of the statement succeeds, the transaction is committed, if it does
not, the transaction is rolled back.
Implicit Transactions
In this mode, SQL Server automatically starts a new transaction when the previous one has
been committed or rolled back. The transaction must then be explicitly committed or rolled
Page 5 of 9
CCI – Computer Science Dept 655445336.doc
The mode can be switched between Autocommit and Implicit Transactions using the SET
statement as follows (it can be set to ON or OFF):
This mode is part of the SQL99 standard, so all RDBMS applications should provide it.
Explicit Transactions
In this mode, transactions must be explicitly started and ended using BEGIN
TRANSACTION, COMMIT TRANSACTION and ROLLBACK TRANSACTION.
Explicit transactions can be used at any time i.e. if the Implicit_Transactions mode is on or
off.
A lock is access to an object that is granted to a particular transaction. The lock also restricts
access to the object from other transactions that are competing for the same resource.
If more than one transaction requires access to the data, they are queued up for the lock – so
when one transaction completes, the next one can then get access to the data. This is also
known as serialization.
Locks are expensive in terms of database resources – obtaining and setting locks add to the
time required to carry out transactions, and also cause other transactions to take longer as
they wait for locks to be released. However, if the competing transaction just wants to read
data, it is not necessary to completely block access to the object.
To minimise the overhead, different levels of locking can be assigned. In SQL Server, this
level is known as the Isolation Level.
Page 6 of 9
CCI – Computer Science Dept 655445336.doc
The isolation level can also be described as the level at which a transaction is prepared to
accept inconsistent data or the degree to which one transaction must be isolated from other
transactions.
A lower isolation level means that more transactions can occur at the same time – this
increases concurrency. But this is at the expense of correctness of the data – because some
transactions may gain access to data that is in the process of being changed by a transaction.
A higher isolation level ensures that data is always correct but the degree of concurrency can
be negatively affected – because access is granted to queued transactions only when data is
not being used by any transaction.
In this example, we cannot delete the Department while there are still Employees associated
with it – this is because of the foreign key constraint between the two tables.
Let us assume that we are given the name for the new Department and the DepartmentID of
the department that is to be deleted. Then, the steps to carry out the complete process are as
follows (bearing in mind that the foreign key constraint between the Employees and
Departments tables will not allow for a Department to be deleted if there are associated
records in the Employees table):
After it has been declared, a variable can be referenced in the batch of SQL
The PRINT keyword prints the text following it out to the results pane.
Another way to get the ID value is to use the global variable @@identity – when this is
selected, it returns the last identity value generated by the previous insert.
GO
5 SQL Programming
This section is to provide you with a brief introduction to programming in T-SQL.
The section above introduced variables and showed how a variable may be used in T-SQL
code. The above example was within a stored procedure, however, a series of SQL statements
can be saved in a text file and treated simply as a batch that can be opened in the Query
Analyzer and executed at any time.
The details given here are for SQL Server's T-SQL only – they are not part of the SQL99
standard. However, other RDBMS applications provide their own programming languages
e.g .Oracle has PL/SQL.
The table below lists some elements of the control-of-flow language provided with T-SQL.
Keywords Description
BEGIN…END Marks the beginning and end of a block of SQL statements. Must be used to
delimit a 'statement_block', where one appears in the syntax for another construct
– see, for example, the IF/ELSE and WHILE/BREAK statements below.
Page 8 of 9
CCI – Computer Science Dept 655445336.doc
IF… ELSE Test for a condition, and if it is true, execute the first block of code; if not true,
IF Boolean_expression execute the block specified after the ELSE. If ELSE is not specified, flow
{ sql_statement | continues to the next statement. The condition is an expression that returns true or
statement_block } false.
[ ELSE See example below - note the use of BEGIN and END – this is necessary if more
{ sql_statement | than one line of code is to be executed when the condition is true or when it is
statement_block } ] false; also note that the condition can be the comparison of the result of a select
statement with a value:
Page 9 of 9