Hàm CASE trong SQL Server
Trong SQL Sever, hàm CASE kim định giá tr da trên danh sách điu kin
đưa ra, sau đó tr v mt hoc nhiu kết qu. bài này chúng tôi s minh ho
mt s cách dùng khác nhau ca hàm này trong nhng trường hp khác nhau.
Phương thc 1: Cách dùng hàm CASE đơn gin
Đây là cách dùng ph biến nht ca hàm case, trong đó bn có th to giá tr vô hướng da trên
danh sách điu kin đưa ra.
Gi s chúng ta có bng sau vi các ct id (mã s nhân viên), [First name] (tên), [Last name]
(h) và gender (gii tính). Bây gi, chúng ta mun to thêm tin t (Mr, Ms) phía trước tng
tên, da trên giá tr ca ct Gender, thc hin như sau:
use tempdb
go
if exists (select * from dbo.sysobjects where id = object_id(N'[emp]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [emp]
GO
create table Emp (id int, [First name] varchar(50),
[Last name] varchar(50), gender char(1))
go
insert into Emp (id,[First name],[Last name], gender )
values (1,'John','Smith','m')
insert into Emp (id,[First name],[Last name], gender )
values (2,'James','Bond','m')
insert into Emp (id,[First name],[Last name], gender )
values (3,'Alexa','Mantena','f')
insert into Emp (id,[First name],[Last name], gender )
values (4,'Shui','Qui','f')
insert into Emp (id,[First name],[Last name], gender )
values (5,'William','Hsu','m')
insert into Emp (id,[First name],[Last name], gender )
values (6,'Danielle','Stewart','F')
insert into Emp (id,[First name],[Last name], gender )
values (7,'Martha','Mcgrath','F')
insert into Emp (id,[First name],[Last name], gender )
values (8,'Henry','Fayol','m')
insert into Emp (id,[First name],[Last name], gender )
values (9,'Dick','Watson','m')
insert into Emp (id,[First name],[Last name], gender )
values (10,'Helen','Foster','F')
go
Bây gi, to ct [Full name] (h tên đầy đủ) để xác định nên đặt tin t là “Mr.” hay “Ms.”, da
vào giá tr trên ct Gender.
Select [id],[Full Name] = case Gender
when 'm' then 'Mr. '+[First name]+ ' '+[Last name]
when 'f' then 'Ms. '+[First name]+ ' '+[Last name]
end
from Emp
Th tc này tr v kết qu như hình bên dưới:
id Full Name
----------- ----------------
1 Mr. John Smith
2 Mr. James Bond
3 Ms. Alexa Mantena
4 Ms. Shui Qui
5 Mr. William Hsu
6 Ms. Danielle Stewart
7 Ms. Martha Mcgrath
8 Mr. Henry Fayol
9 Mr. Dick Watson
10 Ms. Helen Foster
Phương thc 2: S dng hàm case đơn gin vi mnh đề ELSE
Nếu thêm mt hàng vi giá tr NULL vào ct gender, bn s không thy có tên nào được tr v
trong tp hp kết qu.
Chèn hàng sau vào bng emp:
use tempdb
go
insert into Emp (id,[First name],[Last name], gender ) values
(11,'Tom','Gabe',NULL)
go
Bây gi to ct [Full name] để xác định tin t đặt trước mi tên là “Mr.” hay “Ms.”, da trên
giá tr ly ct Gender:
Select [id],[Full Name] = case Gender
when 'm' then 'Mr. '+[First name]+ ' '+[Last name]
when 'f' then 'Ms. '+[First name]+ ' '+[Last name]
end
from Emp
Kết qu tr v như sau:
id Full Name
----------- ------------------------
1 Mr. John Smith
2 Mr. James Bond
3 Ms. Alexa Mantena
4 Ms. Shui Qui
5 Mr. William Hsu
6 Ms. Danielle Stewart
7 Ms. Martha Mcgrath
8 Mr. Henry Fayol
9 Mr. Dick Watson
10 Ms. Helen Foster
11 NULL
Tuy nhiên, chúng ta cn hin th Full Name (h tên đầy đủ) ca nhân viên, k c trong trường
hp không có giá tr trên Gender.
Để thc hin điu này, bn cn dùng hàm CASE vi mnh đề ELSE. Thc hin truy vn như
sau:
Select [id],[Full Name] = case Gender
when 'm' then 'Mr. '+[First name]+ ' '+[Last name]
when 'f' then 'Mz. '+[First name]+ ' '+[Last name]
else [First name]+ ' '+[Last name]
end
from Emp
Kết qu tr v như sau:
id Full Name
----------- ----------------------
1 Mr. John Smith
2 Mr. James Bond
3 Mz. Alexa Mantena
4 Mz. Shui Qui
5 Mr. William Hsu
6 Mz. Danielle Stewart
7 Mz. Martha Mcgrath
8 Mr. Henry Fayol
9 Mr. Dick Watson
10 Mz. Helen Foster
11 Tom Gabe
Phương thc 3: S dng hàm CASE khi có hai hoc nhiu điu kin trong danh sách
Trong hai ví d trên, bn thy rng các điu kin được xét đến hoc là Male, Female, hay None.
Tuy nhiên, trong nhiu trường hp bn s cn s dng nhiu điu kin, nhiu toán t cùng lúc để
tr v mt giá tr.
Thêm ct [Marital Status] (tình trng hôn nhân) vào bng và update giá tr như bên dưới:
use tempdb
go
alter table Emp add [Marital Status] char(1) -- S-Single M-Married
go
Update Emp set [Marital Status]='S' where id in (1,5,8)
Update Emp set [Marital Status]='M' where [Marital Status] is NULL
Go
Gi s chúng ta mun hin th tên nhân viên có tin t đứng trước giúp d dàng xác định tình
trng hôn nhân ca h. Thc hin truy vn như sau:
Select [id],[Full Name] = case
when Gender ='m' and [marital status] ='S' then 'MR. '+[First name]+ '
'+[Last name]
when Gender ='m' and [marital status] ='M' then 'Mr. '+[First name]+ '
'+[Last name]
when Gender ='f' and [marital status] ='S' then 'Ms. '+[First name]+ '
'+[Last name]
when Gender ='f' and [marital status] ='M' then 'Mrs. '+[First name]+ '
'+[Last name]
else [First name]+ ' '+[Last name]
end
from Emp
Kết qu được tr v là:
id Full Name
----------- --------------------
1 MR. John Smith
2 Mr. James Bond
3 Mrs. Alexa Mantena
4 Mrs. Shui Qui
5 MR. William Hsu
6 Mrs. Danielle Stewart
7 Ms. Martha Mcgrath
8 MR. Henry Fayol
9 Mr. Dick Watson
10 Mrs. Helen Foster
11 Tom Gabe
Kết lun
phn mt này chúng ta đã thy mt s ví d minh ho các cách s dng hàm CASE đơn gin
trong truy vn SQL. Trong phn 2 chúng ta s tiếp tc tho lun cách s dng hàm CASE
nhng trường hp phc tp.
Trong phn 1 ca lot bài này chúng tôi đã gii thích các s dng hàm CASE đơn gin trong truy
vn. Trong phn II này, chúng tôi s tiếp tc tho lun v cách s dng hàm CASE trong mt s
trường hp khác.
Phương thc 4: S dng hàm CASE trong tìm kiếm
Gi s chúng ta có bng sau
use tempdb
go
if exists (select * from dbo.sysobjects
where id = object_id(N'[emp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [emp]
GO
create table Emp
(id int, [First name] varchar(50), [Last name] varchar(50), Salary money)
go
insert into Emp (id,[First name],[Last name], salary )
values (1,'John','Smith',120000)
insert into Emp (id,[First name],[Last name], salary )
values (2,'James','Bond',95000)
insert into Emp (id,[First name],[Last name], salary )
values (3,'Alexa','Mantena',200000)
insert into Emp (id,[First name],[Last name], salary )
values (4,'Shui','Qui',36000)
insert into Emp (id,[First name],[Last name], salary )
values (5,'William','Hsu',39000)
insert into Emp (id,[First name],[Last name], salary )
values (6,'Danielle','Stewart',50000)
insert into Emp (id,[First name],[Last name], salary )
values (7,'Martha','Mcgrath',400000)
insert into Emp (id,[First name],[Last name], salary )
values (8,'Henry','Fayol',75000)
insert into Emp (id,[First name],[Last name], salary )
values (9,'Dick','Watson',91000)
insert into Emp (id,[First name],[Last name], salary )
values (10,'Helen','Foster',124000)
go
Và gi mun to thêm mt ct Tax (thuế) da trên mc lương như sau
Select [id],[Full Name]=[First name]+ [Last name],Salary,Tax = case
When salary between 0 and 36000 then Salary*.24
When salary between 36000 and 450000 then Salary*.28
When salary between 45000 and 75000 then Salary *.30
When salary between 75000 and 150000 then Salary *.32
else Salary*.40 end
from Emp
Hàm này s cho kết qu:
id Full Name Salary Tax
----------- -------------------------------- ---------------------
1 JohnSmith 120000.00 33600.000000
2 JamesBond 95000.00 26600.000000
3 AlexaMantena 200000.00 56000.000000
4 ShuiQui 36000.00 8640.000000
5 WilliamHsu 39000.00 10920.000000
6 DanielleStewart 50000.00 14000.000000
7 MarthaMcgrath 400000.00 112000.000000
8 HenryFayol 75000.00 21000.000000
9 DickWatson 91000.00 25480.000000
10 HelenFoster 124000.00 34720.000000
Phương thc 5: S dng hàm CASE trong mnh đề ORDER BY
Gi s chúng ta có bng dưới trong Books:
use tempdb
go
if exists (select * from dbo.sysobjects where id = object_id(N'[Books]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)