Sometimes the data retrieved from the database needs to be formatted. For example, if gender is stored in the database, 1 indicates male, 0 indicates female, and 1 indicates male, 0 is replaced by female. The methods here are diverse and can be performed on the server or on the client.
There are two ways to use SQL query statements on the server.
Method 1: Use case
Declare @ tb table (name char (5), sex int)
Insert @ tb select 'andy ', 1 union all
Select 'Jim ', 1 union all
Select 'lily', 0 union all
Select 'linda ', null
Select
Name,
Sex = CASE
WHEN sex = 1 THEN 'male'
When sex = 0 then 'female'
End
From @ tb
Result:
Name sex
---------
Andy male
Jim male
Lily
Linda NULL
Method 2 Use join
Declare @ tb table (name char (5), sex int)
Insert @ tb select 'andy ', 1 union all
Select 'Jim ', 1 union all
Select 'lily', 0 union all
Select 'linda ', null
Select t. name, t. sex, s. SexTitle
From @ tb t left join
(Select 1 as SexID, 'male' as SexTitle union all select 0, 'female ') s
On t. sex = s. SexID
Result:
Name sex SexTitle
------------------------
Andy 1 male
Jim 1 male
Lily 0 female
Linda NULL