SlideShare a Scribd company logo
Basics of T-SQL programming
Declaring variables and Parameters
1
• A local variable is defined using the DECLARE statement.
• The name of the local variable needs to start with the @ symbol
as the first character of its name.
Example: DECLARE @Count INT
• More than one variable can be defined with a single DECLARE
statement with a comma
Example: DECLARE @Count INT, @X INT, @Y INT, @Z
• 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.
• Using SET:-
DECLARE @Count INT
SET @Count = 1
• Using SELECT statement to initialize the value of a local
variable with the value returned from a select that fetch the total
number of rows in the customer table.
declare @rowcount int
select @rowcount=(selectcount(*)from customer
print @rowcount
2
• An example that returns all the Customers records in the sales
database where the customer’s address column is equal to ‘Bahir
Dar’
declare @myaddress varchar(50)
set @myaddress='bahir dar'
select*from customer where [address]=@myaddress
Example
declare @var1 int,@var2 float,@var3 int,@sum int
set @var1=10
set @var2=20
set @var3=30
set @sum=@var1+@var2+@var3
print @sum
N.B.you can also use select to assign and to
display
3
IF ... ELSE statement
• T-SQL has the IF statement to help with allowing different code to be
executed based on the results of a condition.
• Format one:
IF <condition> <then code to be executed >
• Format two:
IF <condition> <then code to be executed >
ELSE < else code to be executed >.
• If a block of code is used then it will need to be enclosed in a BEGIN
and END statement.
Declare @x int
set @x = 29
if @x = 29 print 'The number is 29'
if @x = 30 print 'The number is 30'
• 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. 4
Example
if(selectcount(*)from customer)<20
print'Number of customer is less than 20’
• If a SELECT statement is used the statement needs to be enclosed in parentheses.
parentheses.
Example
if (select count(*) from Student
where fname like '[A-D]%') > 0
print 'A-D Students are Found ‘
Example
if db_name() = 'master'
begin
Print 'We are in the Master Database'
Print ‘ ’
Print 'So whatever code you execute must be done carefully'
End
else if db_name() = ‘Library'
begin
Print 'We are in the test Library database ’
Print 'So Enjoy' 5
•Suppose we want to determine whether to update or
add a record to the Customer table in the Sales
database.
if exists(select * from customer where
Customer_ID = 'C-150')
Print 'Need to update'
else
Print 'Need to add new record'
Example
if exists(select*from customer
where customer_id='c-100')
print'record is found'
else
print'record is not found'
6
Example
declare @x int
set @x=-80;
if(@x>0)
begin
print'number is positive'
end
else if(@x<0)
begin
print'number is negative'
end
else
print'number is zero'
7
WHILE Loop With CONTINUE and BREAK Keywords
• Syntax:
WHILE Boolean_expression
{ sql_statement | statement_block | BREAK | CONTINUE }
{sql_statement | statement_block}
• BREAK: Causes an exit from the innermost WHILE loop.
• CONTINUE: Causes the WHILE loop to restart, ignoring any statements
after the CONTINUE keyword.
Example
DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
END
8
Example : Usage of WHILE Loop with BREAK keyword
DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
IF @intFlag = 4
BREAK;
END
GO
• Example
declare @start int
set @start=65
while(@start<=90)
begin
print char(@start)
set @start+=1
end 9
Example
WHILE (SELECT AVG(ListPrice) FROM Production.Product) < 300
BEGIN
UPDATE Production.Product
SET ListPrice = ListPrice * 2
SELECT MAX(ListPrice) FROM Production.Product
IF (SELECT MAX(ListPrice) FROM Production.Product) > 500
BREAK
ELSE
CONTINUE
END
• In the above example, if the average list price of a product
is less than $300, the WHILE loop doubles the prices
selects the maximum price.
• If the maximum price is less than or equal to $500,
the WHILE loop restarts and doubles the prices again.
• This loop continues doubling the prices until the
maximum price is greater than $500, and then exits
the WHILE loop. 10
CASE… When expressions
•Evaluates a list of conditions and returns one of multiple
possible result expressions.
•The CASE expression has two formats:
- The simple CASE expression compares an expression to
a set of simple expressions to determine the result.
- The searched CASE expression evaluates a set of
Boolean expressions to determine the result. Within a
SELECT statement, the searched CASE expression
allows for values to be replaced in the result set based on
comparison values.
Syntax for The simple CASE expression:
CASE input_expression
WHEN when_expression THEN result_expression [ ...n
]
[ELSE else_result_expression] 11
Example
declare @x int
set @x=20
select
case
when @x>0 then'x is positive'
when @x<0 then'x is negative'
else'x is zero'
endas'My result 1’
Example
declare @my_variable int
set @my_variable=2
select
case @my_variable
when 1 then'the number is one'
when 2 then'the number is two'
else'the number is unknown'
endas'My result 2’
Example
select first_name,
case [address]
when'bahir dar'then'your address is bahir dar'
when'Addis Abeba'then'your address is addis'
when'Gonder'then'your address is gondar'
else'address unknown'
endas'your address'
from customer
orderby first_name
12
Example
select first_name,last_name,
case sex
when'm'then'you are male'
when'f'then'you are female'
else'unknown'
endas'Gender'
from customer
orderby first_name
Example
select first_name,last_name,
case
when sex='m'then'you are male'
when sex='f'then'you are female'
else'unknown'
endas'Gender'
from customer
orderby first_name
13
Exercise
1. Using if …Else statement write a T-
SQL program to print the grade of a
student. Assume that a student table
has (StudId, FN,LN, Age, mark) and
write A if the mark is above 80, B if the
mark is between 79 and 60 and C if is
less than 60
2. Use while… loop write a T-SQL
program to find the factorial of a
number
3. Describe the Syntax of CASE……When14
Use the following sample database for your example
create database sales
use sales
create table customer
(
Customer_ID varchar(50)not null,
First_Name varchar(200)not null,
Last_Name varchar(200) not null,
Sex char(1),
[Address] varchar(255),
primary key(Customer_ID)
)
create table Product
(
Product_ID char(200),
Product_Name varchar(255),
purchase_Price money,
Acquired_Date date,
product_price money,
Manufacturer varchar(255),
primary key(Product_ID)
)
create table [Order]
(
Order_ID int identity(1,1),
Product_ID char(200),
Customer_ID varchar(50),
Order_Date date,
primary key(Order_ID),
foreign key(Product_ID)references
Product(Product_ID),
foreign key(Customer_ID)references
customer(Customer_ID)
)
15
use sales
insert into customer
values('C-100','Birhanu','Bogale','M','Gonder'),
('C-101','Asnakech','Worku','F','Addis Abeba'),
('C-102','Chala','Debele','M','Nazrete'),
('C-103','Dereb', 'Asmamaw','M','Dangla'),
('C-104','Eshetu','Amare','M','Bahir Dar'),
('C-105','Girma', 'Moges','M','Addis Abeba'),
('C-106','Haymanot', 'Degu','F','Mekele'),
('C-107','Alem', 'Tefera','F','Bahir Dar'),
('C-108','Zebider', 'Yetagesu','F','Desse'),
('C-109','Habtam', 'Tegabu','F','Gonder'),
('C-110','Fikir', 'Ashenafi','M','Bahir Dar'),
('C-111','Alex', 'Amanu','M','Bahir Dar'),
('C-112','Ahmed', 'Nuredin','M','Debre Markos'),
('C-113','Aysha', 'Tesfa','F','Debre Tabor'),
('C-114','Befkadu', 'Honelgn','M','Gonder')
16
use sales
insert into product
values('P-100','Stationary',1500,'2013-01-01',2500,'Beuty company'),
('P-101','Hard disk',2700,'2015-03-05',2500,'SeaGate'),
('P-102','Monitor',700,'2015-03-05',1100,'Dell'),
('P-103','Stationary',4000,'2014-07-04',5900,'Sanitation'),
('P-104','Printer',5000,'2013-04-06',2400,'Dell'),
('P-105','Keyboard',350,'2012-02-04',500,'Microsoft'),
('P-106','Computer',5000,'2011-08-02',7400,'Sony'),
('P-107','Laptop',10000,'2013-03-05',13000,'Toshiba'),
('P-108','Camera',1500,'2014-05-01',2600,'Webcam company'),
('P-109','Plotter',5300,'2013-01-02',6800,'SAMSUNG'),
('P-110','Laptop',15000,'2013-01-02',23000,'Lenovo')
17
use sales
insert into [order]
values ('P-108','C-104','2013-03-06'),
('P-108','C-114','2014-05-01'),
('P-100','C-106','2015-08-01'),
('P-103','C-106','2011-02-08'),
('P-109','C-110','1999-01-07'),
('P-110','C-114','1980-04-01'),
('P-102','C-100','2015-01-08'),
('P-104','C-100','2012-03-05'),
('P-101','C-101','2013-04-07'),
('P-105','C-102','2014-09-07'),
('P-106','C-103','1996-01-05'),
('P-107','C-105','2014-03-07'),
('P-104','C-108','2015-02-04'),
('P-102','C-109','2012-02-04'),
('P-109','C-111','2014-03-09'),
('P-100','C-112','2015-04-01'),
('P-105','C-113','2013-08-07'),
('P-110','C-114','1993-07-02'),
('P-104','C-107','2012-05-07') 18

More Related Content

Similar to Advanced DB lab 1 (2).pptx

Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
Mahir Haque
 
ADV Powepoint 4 Lec.pptx
ADV Powepoint 4 Lec.pptxADV Powepoint 4 Lec.pptx
ADV Powepoint 4 Lec.pptx
ArjayBalberan1
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimizationVivek Singh
 
2 BytesC++ course_2014_c2_ flow of control
2 BytesC++ course_2014_c2_ flow of control 2 BytesC++ course_2014_c2_ flow of control
2 BytesC++ course_2014_c2_ flow of control
kinan keshkeh
 
Pointer
PointerPointer
Pointer
Fahuda E
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11Syed Asrarali
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
Shakila Mahjabin
 
Assignment#08
Assignment#08Assignment#08
Assignment#08
Sunita Milind Dol
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2Belal Arfa
 
CHAPTER-3a.ppt
CHAPTER-3a.pptCHAPTER-3a.ppt
CHAPTER-3a.ppt
Tekle12
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Pseudocode
PseudocodePseudocode
Pseudocode
Harsha Madushanka
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankppt
newrforce
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sql
nishantdavid9
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with examplepranav kumar verma
 
Sql
SqlSql
PL-SQL.pdf
PL-SQL.pdfPL-SQL.pdf
PL-SQL.pdf
Anas Nakash
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAP
sapdocs. info
 

Similar to Advanced DB lab 1 (2).pptx (20)

Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
ADV Powepoint 4 Lec.pptx
ADV Powepoint 4 Lec.pptxADV Powepoint 4 Lec.pptx
ADV Powepoint 4 Lec.pptx
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimization
 
2 BytesC++ course_2014_c2_ flow of control
2 BytesC++ course_2014_c2_ flow of control 2 BytesC++ course_2014_c2_ flow of control
2 BytesC++ course_2014_c2_ flow of control
 
Pointer
PointerPointer
Pointer
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
Assignment#08
Assignment#08Assignment#08
Assignment#08
 
Dynamic websites lec2
Dynamic websites lec2Dynamic websites lec2
Dynamic websites lec2
 
CHAPTER-3a.ppt
CHAPTER-3a.pptCHAPTER-3a.ppt
CHAPTER-3a.ppt
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
Chinabankppt
ChinabankpptChinabankppt
Chinabankppt
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sql
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
 
Sql
SqlSql
Sql
 
PL-SQL.pdf
PL-SQL.pdfPL-SQL.pdf
PL-SQL.pdf
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAP
 

Recently uploaded

Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 

Recently uploaded (20)

Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 

Advanced DB lab 1 (2).pptx

  • 1. Basics of T-SQL programming Declaring variables and Parameters 1
  • 2. • A local variable is defined using the DECLARE statement. • The name of the local variable needs to start with the @ symbol as the first character of its name. Example: DECLARE @Count INT • More than one variable can be defined with a single DECLARE statement with a comma Example: DECLARE @Count INT, @X INT, @Y INT, @Z • 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. • Using SET:- DECLARE @Count INT SET @Count = 1 • Using SELECT statement to initialize the value of a local variable with the value returned from a select that fetch the total number of rows in the customer table. declare @rowcount int select @rowcount=(selectcount(*)from customer print @rowcount 2
  • 3. • An example that returns all the Customers records in the sales database where the customer’s address column is equal to ‘Bahir Dar’ declare @myaddress varchar(50) set @myaddress='bahir dar' select*from customer where [address]=@myaddress Example declare @var1 int,@var2 float,@var3 int,@sum int set @var1=10 set @var2=20 set @var3=30 set @sum=@var1+@var2+@var3 print @sum N.B.you can also use select to assign and to display 3
  • 4. IF ... ELSE statement • T-SQL has the IF statement to help with allowing different code to be executed based on the results of a condition. • Format one: IF <condition> <then code to be executed > • Format two: IF <condition> <then code to be executed > ELSE < else code to be executed >. • If a block of code is used then it will need to be enclosed in a BEGIN and END statement. Declare @x int set @x = 29 if @x = 29 print 'The number is 29' if @x = 30 print 'The number is 30' • 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. 4
  • 5. Example if(selectcount(*)from customer)<20 print'Number of customer is less than 20’ • If a SELECT statement is used the statement needs to be enclosed in parentheses. parentheses. Example if (select count(*) from Student where fname like '[A-D]%') > 0 print 'A-D Students are Found ‘ Example if db_name() = 'master' begin Print 'We are in the Master Database' Print ‘ ’ Print 'So whatever code you execute must be done carefully' End else if db_name() = ‘Library' begin Print 'We are in the test Library database ’ Print 'So Enjoy' 5
  • 6. •Suppose we want to determine whether to update or add a record to the Customer table in the Sales database. if exists(select * from customer where Customer_ID = 'C-150') Print 'Need to update' else Print 'Need to add new record' Example if exists(select*from customer where customer_id='c-100') print'record is found' else print'record is not found' 6
  • 7. Example declare @x int set @x=-80; if(@x>0) begin print'number is positive' end else if(@x<0) begin print'number is negative' end else print'number is zero' 7
  • 8. WHILE Loop With CONTINUE and BREAK Keywords • Syntax: WHILE Boolean_expression { sql_statement | statement_block | BREAK | CONTINUE } {sql_statement | statement_block} • BREAK: Causes an exit from the innermost WHILE loop. • CONTINUE: Causes the WHILE loop to restart, ignoring any statements after the CONTINUE keyword. Example DECLARE @intFlag INT SET @intFlag = 1 WHILE (@intFlag <=5) BEGIN PRINT @intFlag SET @intFlag = @intFlag + 1 END 8
  • 9. Example : Usage of WHILE Loop with BREAK keyword DECLARE @intFlag INT SET @intFlag = 1 WHILE (@intFlag <=5) BEGIN PRINT @intFlag SET @intFlag = @intFlag + 1 IF @intFlag = 4 BREAK; END GO • Example declare @start int set @start=65 while(@start<=90) begin print char(@start) set @start+=1 end 9
  • 10. Example WHILE (SELECT AVG(ListPrice) FROM Production.Product) < 300 BEGIN UPDATE Production.Product SET ListPrice = ListPrice * 2 SELECT MAX(ListPrice) FROM Production.Product IF (SELECT MAX(ListPrice) FROM Production.Product) > 500 BREAK ELSE CONTINUE END • In the above example, if the average list price of a product is less than $300, the WHILE loop doubles the prices selects the maximum price. • If the maximum price is less than or equal to $500, the WHILE loop restarts and doubles the prices again. • This loop continues doubling the prices until the maximum price is greater than $500, and then exits the WHILE loop. 10
  • 11. CASE… When expressions •Evaluates a list of conditions and returns one of multiple possible result expressions. •The CASE expression has two formats: - The simple CASE expression compares an expression to a set of simple expressions to determine the result. - The searched CASE expression evaluates a set of Boolean expressions to determine the result. Within a SELECT statement, the searched CASE expression allows for values to be replaced in the result set based on comparison values. Syntax for The simple CASE expression: CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ELSE else_result_expression] 11
  • 12. Example declare @x int set @x=20 select case when @x>0 then'x is positive' when @x<0 then'x is negative' else'x is zero' endas'My result 1’ Example declare @my_variable int set @my_variable=2 select case @my_variable when 1 then'the number is one' when 2 then'the number is two' else'the number is unknown' endas'My result 2’ Example select first_name, case [address] when'bahir dar'then'your address is bahir dar' when'Addis Abeba'then'your address is addis' when'Gonder'then'your address is gondar' else'address unknown' endas'your address' from customer orderby first_name 12
  • 13. Example select first_name,last_name, case sex when'm'then'you are male' when'f'then'you are female' else'unknown' endas'Gender' from customer orderby first_name Example select first_name,last_name, case when sex='m'then'you are male' when sex='f'then'you are female' else'unknown' endas'Gender' from customer orderby first_name 13
  • 14. Exercise 1. Using if …Else statement write a T- SQL program to print the grade of a student. Assume that a student table has (StudId, FN,LN, Age, mark) and write A if the mark is above 80, B if the mark is between 79 and 60 and C if is less than 60 2. Use while… loop write a T-SQL program to find the factorial of a number 3. Describe the Syntax of CASE……When14
  • 15. Use the following sample database for your example create database sales use sales create table customer ( Customer_ID varchar(50)not null, First_Name varchar(200)not null, Last_Name varchar(200) not null, Sex char(1), [Address] varchar(255), primary key(Customer_ID) ) create table Product ( Product_ID char(200), Product_Name varchar(255), purchase_Price money, Acquired_Date date, product_price money, Manufacturer varchar(255), primary key(Product_ID) ) create table [Order] ( Order_ID int identity(1,1), Product_ID char(200), Customer_ID varchar(50), Order_Date date, primary key(Order_ID), foreign key(Product_ID)references Product(Product_ID), foreign key(Customer_ID)references customer(Customer_ID) ) 15
  • 16. use sales insert into customer values('C-100','Birhanu','Bogale','M','Gonder'), ('C-101','Asnakech','Worku','F','Addis Abeba'), ('C-102','Chala','Debele','M','Nazrete'), ('C-103','Dereb', 'Asmamaw','M','Dangla'), ('C-104','Eshetu','Amare','M','Bahir Dar'), ('C-105','Girma', 'Moges','M','Addis Abeba'), ('C-106','Haymanot', 'Degu','F','Mekele'), ('C-107','Alem', 'Tefera','F','Bahir Dar'), ('C-108','Zebider', 'Yetagesu','F','Desse'), ('C-109','Habtam', 'Tegabu','F','Gonder'), ('C-110','Fikir', 'Ashenafi','M','Bahir Dar'), ('C-111','Alex', 'Amanu','M','Bahir Dar'), ('C-112','Ahmed', 'Nuredin','M','Debre Markos'), ('C-113','Aysha', 'Tesfa','F','Debre Tabor'), ('C-114','Befkadu', 'Honelgn','M','Gonder') 16
  • 17. use sales insert into product values('P-100','Stationary',1500,'2013-01-01',2500,'Beuty company'), ('P-101','Hard disk',2700,'2015-03-05',2500,'SeaGate'), ('P-102','Monitor',700,'2015-03-05',1100,'Dell'), ('P-103','Stationary',4000,'2014-07-04',5900,'Sanitation'), ('P-104','Printer',5000,'2013-04-06',2400,'Dell'), ('P-105','Keyboard',350,'2012-02-04',500,'Microsoft'), ('P-106','Computer',5000,'2011-08-02',7400,'Sony'), ('P-107','Laptop',10000,'2013-03-05',13000,'Toshiba'), ('P-108','Camera',1500,'2014-05-01',2600,'Webcam company'), ('P-109','Plotter',5300,'2013-01-02',6800,'SAMSUNG'), ('P-110','Laptop',15000,'2013-01-02',23000,'Lenovo') 17
  • 18. use sales insert into [order] values ('P-108','C-104','2013-03-06'), ('P-108','C-114','2014-05-01'), ('P-100','C-106','2015-08-01'), ('P-103','C-106','2011-02-08'), ('P-109','C-110','1999-01-07'), ('P-110','C-114','1980-04-01'), ('P-102','C-100','2015-01-08'), ('P-104','C-100','2012-03-05'), ('P-101','C-101','2013-04-07'), ('P-105','C-102','2014-09-07'), ('P-106','C-103','1996-01-05'), ('P-107','C-105','2014-03-07'), ('P-104','C-108','2015-02-04'), ('P-102','C-109','2012-02-04'), ('P-109','C-111','2014-03-09'), ('P-100','C-112','2015-04-01'), ('P-105','C-113','2013-08-07'), ('P-110','C-114','1993-07-02'), ('P-104','C-107','2012-05-07') 18