SELECT中的case语句

时间:2016-12-12 01:27:46

标签: sql sql-server

ALTER PROCEDURE Transform.usp_CustomerInfo
AS
BEGIN
    TRUNCATE TABLE [Transform].[CustomerInfo]

    INSERT INTO [Transform].[CustomerInfo] (CustomerName, Total, AvgPurchaseTime, StoreName)
        SELECT
            CASE
               WHEN C.LastName = NULL THEN C.FirstName
               ELSE (C.LastName + ', ' + C.FirstName)
            END AS 'Name', 
            SUM(T.Total),
            D.FullDate,
            UPPER(C.StoreName) AS 'Store Name'
        FROM 
            [Extract].[DimTransaction] AS T
        JOIN 
            [Extract].[DimCustomer] AS C ON T.CustomerID = C.CustomerID
        JOIN 
            [Extract].[DimState] AS S ON C.StateID = S.StateID
        JOIN 
            [Extract].[DimDateTime] AS D ON D.DateTimeID = T.TransactionID
        GROUP BY 
            C.LastName, C.FirstName, D.FullDate, C.StoreName
        ORDER BY 
            Convert(date, D.FullDate, 101) ASC

我想把它拿到哪里如果Last Name出现NULL只使用第一个名字,我想要连接姓氏和名字

3 个答案:

答案 0 :(得分:0)

您可以将其写为:

(CASE WHEN C.LastName IS NULL THEN C.FirstName
      ELSE (C.LastName + ', ' + C.FirstName)
 END) AS Name, 

或者只使用COALESCE()

(COALESE(C.LastName + ', ', '') + C.FirstName) as Name

答案 1 :(得分:0)

NULL不是值,因此不能使用=,<,>与其他价值进行比较。 顺便说一下,你的情况何时陈述也可以用ISNULL

ISNULL(C.LastName + ', ','')+c.FirstName AS Name

答案 2 :(得分:0)

您无法检查为= NULL,但您可以通过以下方式检查默认值,或者您必须采用其他人建议的方式:

CASE WHEN ISNULL(c.lastName,'') = '' THEN 
    -------
ELSE
    -------
END

如果您使用 SQLSERVER2008 + ,那么您也可以使用CONCAT:

CONCAT(ISNULL(c.lastname + ', ',''), c.firstname) as Name