SQL-Case When用法

/*
    人员:LDH
    功能:SQL-Case When用法
    日期:2021-5-14
 */
 
USE TestDB;
 GO
 
CREATE TABLE Employee
    (
      EmpId INT IDENTITY(20210001, 1)
                PRIMARY KEY ,
      EmpName NVARCHAR(20) NOT NULL ,
      EmpAge INT CHECK ( EmpAge BETWEEN 1 AND 150 )
                 DEFAULT 1 ,
      EmpStatus BIT NOT NULL
                    DEFAULT 0 --0:在职 1-离职
                    
    );
    
INSERT  INTO dbo.Employee
        ( EmpName, EmpAge, EmpStatus )
VALUES  ( NJason, 31, 0 ),
        ( NTom, 18, 1 ),
        ( NLucy, 21, 1 ),
        ( NJack, 31, 0 ),
        ( NLily, 18, 1 ),
        ( NFrank, 21, 0 ),
        ( NBush, 51, 0 ),
        ( NApple, 18, 1 ),
        ( NMack, 21, 0 ),
        ( NBlack, 28, 1 ),
        ( NPear, 18, 0 ),
        ( NBanana, 21, 0 );
        
SELECT  EmpId ,
        EmpName ,
        EmpAge ,
        EmpStatus
FROM    dbo.Employee;

-- =============================
-- 方法1
-- =============================

SELECT  EmpId ,
        EmpName ,
        EmpAge ,
        EmpStatus = CASE WHEN EmpStatus = 0 THEN 在职
                           WHEN EmpStatus = 1 THEN 离职
                      END
FROM    dbo.Employee;


-- =============================
-- 方法2
-- =============================
SELECT  EmpId ,
        EmpName ,
        EmpAge ,
        EmpStatus = CASE EmpStatus
                        WHEN 0 THEN 在职
                        WHEN 1 THEN 离职
                      END
FROM    dbo.Employee;

SQL-Case When用法

SQL-Case When用法

上一篇:Linux 安装 mysql


下一篇:本地安装mysql