Replacement and formatting after SQL data retrieval

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.