T-SQL基于条件强制为null值

时间:2014-04-28 11:19:02

标签: sql tsql sql-view

这是我的观点

 SELECT e.Text AS StatusText,
        a.Created AS [DATE],
        a.Username,
        b.Name AS CustomerName,
        c.Name AS ServiceName,
        d.Message AS DeviationMessage
   FROM dbo.StatusUpdate AS a
        LEFT OUTER JOIN dbo.Customer AS b ON a.CustomerId = b.CustomerID
        LEFT OUTER JOIN dbo.Service AS c ON a.ServiceId = c.ServiceID
        LEFT OUTER JOIN dbo.Deviation AS d ON a.DeviationId = d.DeviationID
        LEFT OUTER JOIN dbo.StatusText AS e ON a.Status = e.ID

我想要做的是:当a.Status(int)为2或3时,我想强制a.Username显示为NULL。我该怎么做呢?

2 个答案:

答案 0 :(得分:5)

试试这个:

 SELECT e.Text AS StatusText,
        a.Created AS [DATE],
        CASE a.status
            WHEN 2 THEN NULL
            WHEN 3 THEN NULL
            ELSE a.Username
        END,  
        b.Name  AS CustomerName,
        c.Name  AS ServiceName,
        d.Message AS DeviationMessage
   FROM dbo.StatusUpdate AS a
        LEFT OUTER JOIN dbo.Customer AS b ON a.CustomerId = b.CustomerID
        LEFT OUTER JOIN dbo.Service AS c ON a.ServiceId = c.ServiceID
        LEFT OUTER JOIN dbo.Deviation AS d ON a.DeviationId = d.DeviationID
        LEFT OUTER JOIN dbo.StatusText AS e ON a.Status = e.ID

答案 1 :(得分:1)

您可以通过案例陈述轻松实现这一目标。

类似

CASE WHEN Status = 3 THEN USERNAME IS NULL

这是未经测试的,但这个想法就在那里。