How to Use Variables, IF and CASE in Database Interactions with TransactSQL - Introducing the IF statement in T-SQL
(Page 3 of 5 )
No programming language exists without the IF statement. It is a conditional control statement which executes a set of statements based on the condition provided by the user. Let us consider the following script:
use northwind
go
declare @EmpSales numeric(12,2)
declare @EmpID int
set @EmpID = 2
set @EmpSales = (select sum(unitprice * quantity)
from [order details]
where orderid in (select orderid from orders
where employeeid=@EmpID))
if @EmpSales > 200000
print 'Good sales: ' + convert(varchar, @EmpSales)
else
print 'Normal sales: ' + convert(varchar, @EmpSales)
go
In the above script, the "IF" condition simply checks whether employee sales have crossed 200000 or not. If the sales value is more than 200K, it prints out the sales value with message "Good Sales." If the sales value is less than (or equal to) 200K, it prints out the sales value with the message "Normal Sales."
If you would like to include more than one statement as part of the true/false parts, you need to embed them within a "begin..end" structure as follows:
use northwind
go
declare @EmpSales numeric(12,2)
declare @EmpID int
set @EmpID = 2
set @EmpSales = (select sum(unitprice * quantity)
from [order details]
where orderid in (select orderid from orders
where employeeid=@EmpID))
if @EmpSales > 200000
begin
print 'Good sales: ' + convert(varchar, @EmpSales)
print 'keep it up'
end
else
begin
print 'Normal sales: ' + convert(varchar, @EmpSales)
print 'Try hard to achieve Good sales'
end
go
Next: Using WHERE conditions in the IF statement >>
More MS SQL Server Articles
More By Jagadish Chaterjee