Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Advanced DB Lab Notes

Main Contents to cover


Variables in SQL Server
Flow Controls
Stored Procedures
Functions
Transactions
Triggers
Security Management
Maintenance and Administration
• Backup, Restore, and cleanup operations
• Performance Tuning
======Variables in MSSQL Server ======
System (Server variables)
Defined by the system and the values of which are computed when they are accessed. The variables
have the prefix @@.

@@CONNECTIONS

Returns the number of connections, or attempted connections, since Microsoft® SQL Server™
was last started.
Syntax
Select @@CONNECTIONS

Return Types
integer
Remarks
Connections are different from users. Applications, for example, can open multiple connections
to SQL Server without the user observing the connections.
To display a report containing several SQL Server statistics, including connection attempts, run
sp_monitor- is a stored procedure(to be seen latter) in the system
sp_help <objectname> to display information about your database objects like tables views
stored procedures or anything you have given name for.
Examples
This example shows the number of login attempts as of the current date and time.
SELECT GETDATE() AS 'Today's Date and Time',
@@CONNECTIONS AS 'Login Attempts'

Other Server variables


select @@SERVERNAME
select @@SERVICENAME
Select @@VERSION
select @@MAX_CONNECTIONS
select @@TRANCOUNT

You can find the list from a number of categories under the functions node in your Database

Page 2 of 18
User defined variables

Defining Variables
Whether you are building a stored procedure or writing a small Query Analyzer script you
will need to know the basics of T-SQL programming.

Local Variables

As with any programming language, T-SQL allows you to define and set variables. A
variable holds a single piece of information, similar to a number or a character string.
Variables can be used for a number of things. Here is a list of a few common variable uses:

• To pass parameters to stored procedures, or function


• To control the processing of a loop
• To test for a true or false condition in an IF statement
• To programmatically control conditions in a WHERE statement

In SQL Server, a variable is typical known as a local variable, due to the scope of the
variable. The scope of a local variable is only available in the batch, stored procedure or
code block in which it is defined. A local variable is defined using the T-SQL "DECLARE"
statement. The name of the local variable needs to start with a "@" sign as the first
character of its name. A local variable can be declared as any system or user defined data
type. Here is a typical declaration for an integer variable named @CNT:

DECLARE @CNT INT

More than one variable can be defined with a single DECLARE statement. To define multiple
variables, with a single DECLARE statement, you separate each variable definition with a
comma, like so:

DECLARE @CNT INT, @X INT, @Y INT, @Z CHAR(10)

Above, I have defined 4 local variables with a single DECLARE statement. A local variable is
initially assigned a NULL value. A value can be assigned to a local variable by using the SET
or SELECT statement. On the SET command you specify the local variable and the value you
wish to assign to the local variable. Here is an example of where I have defined my @CNT
variable and then initialize the variable to 1.

DECLARE @CNT INT


SET @CNT = 1

Here is an example of how to use the SELECT statement to set the value of a local variable.

DECLARE @ROWCNT int


SELECT @ROWCNT=COUNT(*) FROM pubs.dbo.authors

Page 3 of 18
The above example sets the variable @ROWCNT to the number of rows in the
pubs.dbo.authors table.

One of the uses of a variable is to programmatically control the records returned from a
SELECT statement. You do this by using a variable in the WHERE clause. Here is an example
that returns all the Customers records in the Northwind database where the Customers
Country column is equal to 'Germany'

Declare @Country varchar(25)


set @Country = 'Germany'
select CompanyName from Northwind.dbo.Customers
where Country = @Country

=================================Flow Control Structures==========================

IF...ELSE logic

T-SQL has the "IF" statement to help with allowing different code to be executed based on
the results of a condition. The "IF" statement allows a T-SQL programmer to selectively
execute a single line or block of code based upon a Boolean condition. There are two
formats for the "IF" statement, both are shown below:

Format one: IF <condition> <then code to be executed when condition true>

Format two: IF <condition> <then code to be executed when condition


true> ELSE < else code to be executed when condition is false>

In both of these formats, the <condition> is a Boolean expression or series of Boolean


expressions that evaluate to true or false. If the condition evaluates to true, then the "then
code" is executed. For format two, if the condition is false, then the "else code" is executed.
If there is a false condition when using format one, then the next line following the IF
statement is executed, since no else condition exists. The code to be executed can be a
single TSQL statement or a block of code. If a block of code is used then it will need to be
enclosed in a BEGIN and END statement.

Let's review how "Format one" works. This first example will show how the IF statement
would look to execute a single statement, if the condition is true. Here I will test whether a
variable is set to a specific value. If the variable is set to a specific value, then I print out
the appropriate message.

Declare @x int
set @x = 29
if @x = 29 print 'The number is 29'
if @x = 30 print 'The number is 30'

The above code prints out only the phrase "The number is 29", because the first IF
statement evaluates to true. Since the second IF is false the second print statement is not
executed.

Page 4 of 18
Now the condition statement can also contain a SELECT statement. The SELECT statement
will need to return value or set of values that can be tested. If a SELECT statement is used
the statement needs to be enclosed in parentheses.

if (select count(*) from Pubs.dbo.Authors


where au_lname like '[A-D]%') > 0
print 'Found A-D Authors'

Here I printed the message "Found A-D Authors" if the SELECT statement found any authors
in the pubs.dbo.authors table that had a last name that started with an A, B, C, or D.

A code block is created by using a "BEGIN" statement before the first line of code in the
code block, and an "END" statement after that last line of code in the code block. Here is
any example that executes a code block when the IF statement condition evaluates to true.

if db_name() = 'master'
begin
Print 'We are in the Master Database'
Print ''
Print 'So be careful what you execute'
End

Above a series of "PRINT" statements will be executed if this IF statement is run in the
context of the master database. If the context is some other database then the print
statements are not executed.

Sometimes you want to not only execute some code when you have a true condition, but
also want to execute a different set of T-SQL statements when you have a false condition. If
this is your requirement then you will need to use the IF...ELSE construct, that I called
format two above. With this format, if the condition is true then the statement or block of
code following the IF clause is executed, but if the condition evaluates to false then the
statement or block of code following the ELSE clause will be executed

For the first example let's say you need to determine whether to update or add a record to
the Customers table in the Northwind database. The decision is based on whether the
customer exists in the Northwind.dbo.Customers table. Here is the T-SQL code to perform
this existence test for two different CustomerId's.

if exists(select * from Northwind.dbo.Customers


where CustomerId = 'ALFKI')
Print 'Need to update Customer Record ALFKI'
else
Print 'Need to add Customer Record ALFKI'

if exists(select * from Northwind.dbo.Customers


where CustomerId = 'LARSE')
Print 'Need to update Customer Record LARSE'
else
Print 'Need to add Customer Record LARSE'

Page 5 of 18
The first IF...ELSE logic checks to see it CustomerId 'ALFKI' exists. If it exists it prints the
message "Need to update Customer Record", if it doesn't exist the "Need to add Customer
Record" is displayed. This logic is repeated for CustomerId = 'LARS'. When I run this code
against my Northwind database I get the following output.

Need to update Customer Record ALFKI


Need to add Customer Record LARSE

As you can see from the results CustomerId 'ALFKI' existed, because the first print
statement following the first IF statement was executed. Where as in the second IF
statement CustomerId 'LARSE' was not found because the ELSE portion of the IF...ELSE
statement was executed.

If you have complicated logic that needs to be performed prior to determining what T-SQL
statements to execute you can either use multiple conditions on a single IF statement, or
nest your IF statements. Here is a script that determines if the scope of the query is in the
'Northwind' database and if the "Customers" table exists. I have written this query in two
different ways, one with multiple conditions on a single IF statement, and the other by
having nested IF statements.

-- Single IF Statement with multiple conditions


use Northwind
if db_name() = 'Northwind' and
(select count(*) from sysobjects
where name = 'Customers') = 1
print 'Table Customers Exist'
else
print 'Not in the Northwind database' +
' or Table Customer does not exist'

-- Nested IF Statements
use Northwind
if db_name() = 'Northwind'
if (select count(*) from sysobjects
where name = 'Customers') = 1
print 'Table Customers Exist'
else
print 'Table Customer does not exist'
else
print 'Not in the Northwind Database'

How begin…… End statements work


Indicate a block of code to be executed together

Example 1

Without begin and end, the if condition would cause execution of only one SQL statement:

if (select avg(price) from titles) < $15

Page 6 of 18
begin
update titles
set price = price * $2
select title, price
from titles
where price > $28
end

Example 2

Without begin and end, the print statement would not execute:

create trigger deltitle


on titles
for delete
as
if((select count(*) from deleted, salesdetail
where salesdetail.title_id = deleted.title_id) > 0
begin
rollback transaction
print "You can’t delete a title with sales."
end
else
print "Deletion successful--no sales for this
title."

Usage

• begin...end blocks can nest within other begin...end blocks.

Common Usage of Flow-Control in Stored Procedure

There are two most common usage of flow-control which are conditional execution and loop.

Conditional execution with IF-THEN-ELSE and CASE statement

The IF-THEN-ELSE statement is used to evaluate the value of Boolean expression; if the value
is True it execute the block code that follows it otherwise it will execute the block code that
follows by ELSE. The ELSE part is optional in the statement.

Here is a stored procedure which finds the maximum value between two integers using IF-
THEN-ELSE statement. The example is easy just for demonstration.

01.CREATE PROCEDURE FindMax

02. @v1 INT,

03. @v2 INT,

04. @m INT OUTPUT

Page 7 of 18
05.AS

06.BEGIN

07. IF @v1 > @v2

08. SET @m = @v1

09. ELSE

10. SET @m = @v2

11.END

In complex cases, we can use CASE statement instead of IF-THEN-ELSE statement. CASE
statement evaluates a list of Boolean expression and returns one of multiple possible result
expressions. CASE statement is similar to the switch-case statement in other programming
languages such as C/C++, C# or Java. Here is an example of using CASE statement to display
salary level of employee. We have employee table data as follows:

1.employee_id name salary

2.----------- -------- -------

3. 1 jack 3000.00

4. 2 mary 2500.00

5. 3 newcomer 2000.00

6. 4 anna 2800.00

7. 5 Tom 2700.00

8. 6 foo 4700.00

And here is the stored procedure example:

01.CREATE PROCEDURE DisplaySalaryLevel

02.AS

03.BEGIN

04. SELECT employeeId, name,salary, salary_level =

05. CASE

06. WHEN salary < 1000

07. THEN 'very low'

08. WHEN salary > 1000 AND salary < 2000

Page 8 of 18
09. THEN 'low'

10. WHEN salary > 2000 AND salary < 4000

11. THEN 'average'

12. WHEN salary > 4000 AND salary < 10000

13. THEN 'high'

14. WHEN salary > 10000

15. THEN 'very high'

16. END

17. FROM Production.Product

18.END

Looping with WHILE statement

Since T-SQL is fourth generation language and designed to operate with sets of data therefore it
is also possible to write the code to loop through the record set and perform operations on a
single record. Using loop will cause the performance of the server to reduce, but in some cases it
is necessary to use this feature. Example of using WHILE loop statement to calculate the
factorial of an integer number.

01.CREATE PROCEDURE Cal_Factorial

02. @inyN INT,

03. @intFactorial BIGINT OUTPUT

04.AS

05.BEGIN

06. SET @intFactorial = 1

07.

08. WHILE @inyN > 1

09. BEGIN

10. SET @intFactorial = @intFactorial * @inyN

11. SET @inyN = @inyN - 1

12. END

13.END

Page 9 of 18
SQL CASE Expression

A special scalar expression in SQL language is CASE expression. SQL CASE expression is used
as a kind of IF-THEN-ELSE statement. It is similar to switch statement in modern programming
language such as Java or C#. The syntax of the CASE statement is simple as follows:

1.CASE
2. WHEN condition1 THEN result1
3. WHEN condition2 THEN result2
4. ...
5. ELSE result
6.END

The data type of the column_name after the CASE must be the same as the data type of the
expression followed by the keyword THEN or ELSE. The ELSE part of the case expression is
optional. If the ELSE part is omitted and all the conditions in the WHEN does not meet, the
CASE expression will return NULL.

The case expression can be used in anywhere scalar expressions are allowed, including in
WHERE and HAVING clause of the select statement.

It is more intuitive to demonstrate CASE expression through an example. Here is the employees
table for demonstration :

1.employee_id name department_id job_id salary


2.----------- -------- ------------- ------ -------
3. 3 newcomer (NULL) 0 2000.00
4. 2 mary 2 2 2500.00
5. 5 Tom 2 2 2700.00
6. 4 anna 1 1 2800.00
7. 1 jack 1 1 3000.00
8. 6 foo 3 3 4700.00

We can use the CASE expression to print out the employee name, his salary and a computed
column which is called salary level. Here is the sql query:

1.SELECT name,salary,
2.CASE
3.WHEN salary <= 2000 THEN 'low'
4.WHEN salary > 2000 AND salary <= 3000 THEN 'average'
5.WHEN salary > 3000 THEN 'high'
6.END AS salary_level
7.FROM employees
8.ORDER BY salary ASC

Page 10 of 18
The logic is simple if the salary of the employee lower than 2000 the salary level is low; greater
than 2000 and less than or equal to 300, the salary level is average; And greater than 3000, the
salary level is high (of course just for example). And the output is :

1.name salary salary_level


2.-------- ------- ------------
3.newcomer 2000.00 low
4.mary 2500.00 average
5.Tom 2700.00 average
6.anna 2800.00 average
7.jack 3000.00 average
8.foo 4700.00 high

Example: Assume you have an employee table. Compute the income tax on the salary of
employees based on the following progressive tax schedule
Salary level Tax Rate

< = 150 0.00


Between 151-650 0.10
Between 651-1200 0.15
Between 1201-2200 0.20
Between 2201-3500 0.25
Between 3501-5000 0.30
>5000 0.35

The following is the code to compute the income tax for each employee based on his salary

Select EID, Salary, Tax=


Case
When salary <=150 then 0
When salary between 151 And 650 then (Salary-150)*0.1
When salary between 651 And 1200 then
(650-150) * 0.1 + (salary-650) *0.15
When salary between 1201 And 2200 then
(650-150) * 0.1 + (1200-650) *0.15 + (salary-1200)*0.2
When salary between 2201 And 3500 then
(650-150) * 0.1 + (1200-650) *0.15 +(2200-1200)*0.2 +(salary -2200) *0.25
When salary between 3500 And 4000 then
(650-150) * 0.1 + (1200-650) *0.15 +(2200-1200)*0.2 +(3500 -2200) *0.25 +(salary-
3500)*0.30
When salary >5000 then

Page 11 of 18
(650-150) * 0.1 + (1200-650) *0.15 +(2200-1200)*0.2 +(3500 -2200) *0.25 +(4000-
3500)*0.30 + (salary-4000)*0.35
END
FROM EMPLOYEE

T-SQL Programming
/*===============================Transaction management =======================

•Define a transaction by enclosing SQL statements and procedures within the phrases begin
transaction and commit. If you set chained transaction mode, Adaptive
Server implicitly invokes a begin transaction before the following statements: delete,
insert, open, fetch, select, and update. You must still explicitly close the transaction
with a commit.
==>Syntax to commit =>commit tran[saction][ tran_name]
•To cancel all or part of a transaction, use the rollback command. The rollback command
must appear within a transaction; you cannot roll back a transaction after it is committed.
==>Syntax to rollback => rollback tran[saction] [tran_name]
Every begin transaction should have a matching commit or Rollback statement.
Whenever the name of a transaction is not stated in a commit or rollback statement, it applies
to the last transaction issued.

For nested transactions the commit of the outermost transactions start the commit process the
inner ones will not be effected until after the outermost has committed.
*/
Select @@trancount as "Num Of Transaction" -- to see the number of current transactions
begin tran t1
begin
if((select count(*) from telephoneNumber) >2)
begin
update payment set charge = charge *1.1
print ' Charge Amount updated by 10% increase'
end
else
print 'less than three telephone numbers'
Select @@trancount as "Num Of Transaction"

Page 12 of 18
end
commit tran t1
Select @@trancount as "Num of Transaction"

-- Eg write a transaction program that updates the salary of employees in a differential increase
until the average salary is not more than or equal to 2000 ( use the Employees table in
Northwind database (SQL SERVER 2000))
declare @avgSalary money
set @avgSalary = (select avg(salary) from employees)
while (@avgSalary < 2000)
begin
Begin tran
update employees set salary =
case
when titleofCourtesy='Mr.' or titleofCourtesy='Ms.' then
salary*1.1
when titleofCourtesy='Mrs.' then
salary*1.2
when titleofCourtesy='Dr.' then
salary*1.5
else
salary
end
if ( (select Avg(Salary) from employees)> =2000)
begin
set @avgSalary=(select Avg(Salary) from employees)
print 'Average salary exceeded; Transaction rolled back'
Rollback
end
else
commit
end

-- such transaction programs can be formulated in to a stored procedure

/*============================stored procedures===============================

Page 13 of 18
Why should you use stored procedures? Take a look at the key benefits of this technology:

• Precompiled execution. SQL Server compiles each stored procedure once and then
reutilizes the execution plan. This results in tremendous performance boosts when stored
procedures are called repeatedly.
• Reduced client/server traffic. If network bandwidth is a concern in your environment,
you'll be happy to learn that stored procedures can reduce long SQL queries to a single
line that is transmitted over the wire.
• Efficient reuse of code and programming abstraction. Stored procedures can be used
by multiple users and client programs. If you utilize them in a planned manner, you'll find
the development cycle takes less time.
• Enhanced security controls. You can grant users permission to execute a stored
procedure independently of underlying table permissions.

System Stored Procedures


Many of your administrative activities in Microsoft® SQL Server™ 2000 are performed through
a special kind of procedure known as a system stored procedure. System stored procedures are
created and stored in the master database and have the sp_ prefix. System stored procedures can
be executed from any database without having to qualify the stored procedure name fully using
the database name master.
It is strongly recommended that you do not create any stored procedures using sp_ as a prefix.
SQL Server always looks for a stored procedure beginning with sp_ in this order:
1. The stored procedure in the master database.
2. The stored procedure based on any qualifiers provided (database name or owner).
3. The stored procedure using dbo as the owner, if one is not specified.
Therefore, although the user-created stored procedure prefixed with sp_ may exist in the current
database, the master database is always checked first, even if the stored procedure is qualified
with the database name.

Important: If any user-created stored procedure has the same name as a system stored
procedure, the user-created stored procedure will never be executed.

User Defined Stored Procedures


• In order to create your own stored procedures use the following syntax

CREATE PROC [ EDURE ] procedure_name


[ { @parameter data_type }
[ = default ] [ INPUT|OUTPUT ]]

Page 14 of 18
Your stored procedures can be called from your client application- hence they ease the
interaction of application and Databases

Create ---> to create a stored procedure


Alter ---> to modify an existing stored procedure
Drop ----> to delete an existing stored procedure
Exec ----> to execute a stored procedure on the SQL server client utility(Query Analyzer)
*/

-- Consider the following example to view an employee with the parameter


Create proc ViewEmployeea
as
select * from employee
Go
-- Consider the following example to delete an employee with the parameter
Create proc deleteemp @empId int, @sex char(1)
as
delete from employee where empId=@empId
Go
exec deleteemp 2,'F'

-- Stored procedures are most of the time used to do the Data Manipulation Languages.
-- using parameters (both input and output) makes it easier to communicate with a client
application.

Also talk about system stored procedure i.e sp_xxxx

/*=================================Triggers===================================

A trigger is a database object that is attached to a table. In many aspects it is similar to a stored
procedure. As a matter of this fact, triggers are often referred to as a "special kind of stored
procedure."
The main difference between a trigger and a stored procedure is that the former is attached
to a table and is only fired when an INSERT, UPDATE or DELETE occurs. You specify the
modification action(s) that fire the trigger when it is created.

Page 15 of 18
/*
Two special tables are used in trigger statements: the deleted table and the inserted table.
Microsoft® SQL Server™ 2000 automatically creates and manages these tables. You can use
these temporary, memory-resident tables to test the effects of certain data modifications and
to set conditions for trigger actions; however, you cannot alter the data in the tables directly.
*/

The inserted and deleted tables are used primarily in triggers to:

• Extend referential integrity between tables.

• Insert or update data in base tables underlying a view.

• Check for errors and take action based on the error.

• Find the difference between the state of a table before and after a data modification and
take action(s) based on that difference.

Create ---> to create a new trigger


Alter ---> to modify an existing trigger
Drop ----> to delete an existing trigger

Assume UserAccount Schema to be (userName, password, UserType)

*/
Create trigger Checkpasslength
on UserAccount
for insert, update
as
begin
if((select len(password) from inserted) <6)
begin
print 'password should be more than 6 characters; Insert has failed, retry again'
rollback transaction
end
else
print 'Insert successful'
end

Page 16 of 18
-- see the example below

Insert into UserAccount values('username','pass','Administrator')

--eg. Write trigger program that protects the deletion of employees who manages a branch

create trigger empDel


on employee
for delete
as
begin
if ((select count(*) from deleted d, branch b where d.eid= b.eid)>0)
Begin
Print 'you cannot delete an employee who manages a branch'
Rollback transaction
end
else
Print 'Deletion is successful'
end

/*Eg. Write a trigger program that accumulates number of daily subscribers automatically
assume you have subscribers and subscriberslog tables as defined below */

Create table subscribers ( names varchar(100), id int primary key)


Create table subscribersLog (subscribersNum int, LogDate nvarchar (20) primary key)
--the trigger defined below
Create trigger addsubscribers
on subscribers
for insert
as
begin
if((select count(*) from inserted )> 0)
begin
if exists(select * from subscriberslog where logDate = datename(weekday,getDate()))
begin

Page 17 of 18
update subscribersLog set SubscribersNum = SubscribersNum +(select count(*) from inserted )
where logDate=datename(weekday,getDate())
end
else
begin
declare @num int
set @num =(select count(*) from inserted)
insert subscribersLog values( @num ,datename(weekday,getDate()))
end
end
select subscribersNum as "No of Subscribers", LogDate as " By this day" from subscribersLog
end

--then use the following insert statements


insert subscribers values ('username', 4)
insert subscribers values ('urname',6) -- for each insert statement, the trigger is fired

Maintenance Tasks
This will be shown with the GUI on organizing a backup plan, and a cleanup task with
maintenance operations.
Also, will have to show, how to restore a database from a backup device.

Apart from database backup and recovery, the maintenance operations can also be used for
other purposes like performance tuning. Updating statistics etc. will show some from that as
well.

Page 18 of 18

You might also like