WHEN bieuthuc_1 THEN ketqua_1
WHEN bieuthuc_2 THEN ketqua_2
.
WHEN bieuthuc_n THEN ketqua_n
ELSE ketqua_khac
END
Or Searched CASE
CASE
WHEN dieukien_1 THEN ketqua_1
WHEN dieukien_2 THEN ketqua_2
.
WHEN dieukien_n THEN ketqua_n
ELSE ketqua_khac
END
Parameters :
Note :
Take a look and explore some examples of CASE statements in SQL Server.
Example 1: Simple CASE
Suppose you need to check the section of the TipsMake.com website, based on the Code column of the conversion table:
SELECT tenchuyenmuc, Code
(CASE code
WHEN 01 THEN 'Laptrinh-TipsMake.com'
WHEN 02 THEN 'Congnghe-TipsMake.com'
WHEN 03 THEN 'Cuocsong-TipsMake.com'
ELSE 'Khoahoc-TipsMake.com'
END) AS Chuyenmuc
FROM chuyenmuc
ORDER BY Code
Results returned:
tenchuyenmuc Code Chuyenmuc SQL Server 01 Laptrinh-TipsMake.com Linux 02 Congnghe-TipsMake.com Python 01 Laptrinh-TipsMake.com JavaScript 01 Laptrinh-TipsMake.com Android 02 Congnghe-TipsMake.com Giai tri 03 Cuocsong-TipsMake.com Cuocsong-TipsMake.com Science Curve 04 Khoahoc-TipsMake.com Kham pha Science 05 Khoahoc-TipsMake.comExample 2: Searched CASE
SELECT tenchuyenmuc,
CASE
WHEN code = 01 THEN 'Laptrinh-TipsMake.com'
WHEN code = 02 THEN 'Congnghe-TipsMake.com'
WHEN code = 03 THEN 'Cuocsong-TipsMake.com'
ELSE 'Khoahoc-TipsMake.com'
END
FROM chuyenmuc;
You may also not use ELSE conditions like this:
SELECT tenchuyenmuc, Code
(CASE code
WHEN 01 THEN 'Laptrinh-TipsMake.com'
WHEN 02 THEN 'Congnghe-TipsMake.com'
WHEN 03 THEN 'Cuocsong-TipsMake.com'
END) AS Chuyenmuc
FROM chuyenmuc
ORDER BY Code
Or:
SELECT tenchuyenmuc,
CASE
WHEN code = 01 THEN 'Laptrinh-TipsMake.com'
WHEN code = 02 THEN 'Congnghe-TipsMake.com'
WHEN code = 03 THEN 'Cuocsong-TipsMake.com'
END
FROM chuyenmuc;
When the ELSE clause is omitted, if no condition is true, the CASE statement returns NULL.
Example 3: Comparing two conditions
Here is an example that illustrates how to use CASE statements to compare different conditions:
SELECT
CASE
WHEN code < 2 THEN 'Laptrinh-TipsMake.com'
WHEN code = 2 THEN 'Congnghe-TipsMake.com'
END
FROM chuyenmuc;
Remember that the conditions are compared in turn in the order listed. When a condition is determined to be true, the CASE statement will return the result immediately and no other conditions will be evaluated. So you need to be careful when choosing the order that lists your conditions.
See more specific examples of CASE functions in SQL Server
Previous article: Check version information in SQL Server
Next lesson: COALESCE command in SQL Server