ADB Lab Session Guiding Note
ADB Lab Session Guiding Note
ADB Lab Session Guiding Note
@@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'
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:
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:
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:
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.
Here is an example of how to use the SELECT statement to set the value of a local variable.
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'
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:
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.
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.
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.
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.
-- 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'
Example 1
Without begin and end, the if condition would cause execution of only one SQL statement:
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:
Usage
There are two most common usage of flow-control which are conditional execution and loop.
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.
Page 7 of 18
05.AS
06.BEGIN
09. ELSE
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:
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
02.AS
03.BEGIN
05. CASE
Page 8 of 18
09. THEN 'low'
16. END
18.END
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.
04.AS
05.BEGIN
07.
09. BEGIN
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 :
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 :
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
The following is the code to compute the income tax for each employee based on his salary
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
/*============================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.
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.
Page 14 of 18
Your stored procedures can be called from your client application- hence they ease the
interaction of application and Databases
-- 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.
/*=================================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:
• Find the difference between the state of a table before and after a data modification and
take action(s) based on that difference.
*/
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
--eg. Write trigger program that protects the deletion of employees who manages a branch
/*Eg. Write a trigger program that accumulates number of daily subscribers automatically
assume you have subscribers and subscriberslog tables as defined below */
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
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