如何修改要执行的查询?

时间:2012-06-25 09:24:49

标签: sql sql-server-2008-r2

我有以下查询,我希望它显示“Not Yet”,而不是从数据库中显示Status列的NULL值。 怎么做?

SELECT     dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsLog.Username, dbo.SafetySuggestionsStatus.Status,
                 CASE WHEN dbo.SafetySuggestionsStatus.Status  IS NULL THEN 'NOT YET'
FROM         dbo.SafetySuggestionsLog INNER JOIN
                      dbo.employee ON dbo.SafetySuggestionsLog.Username = dbo.employee.Username LEFT OUTER JOIN
                      dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
WHERE     (dbo.employee.Username = @Username)

有关您的信息,该数据库设计如下:

Employee Table: Username, Name
SafetySuggestionsLog Table: ID, Title, Description, Username, StatusID
SafetySuggestionsStatus: ID, Status

2 个答案:

答案 0 :(得分:2)

使用COALESCEISNULL

SELECT     dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsLog.Username, COALESCE(dbo.SafetySuggestionsStatus.Status, "Not Yet") as 'Status'
FROM         dbo.SafetySuggestionsLog INNER JOIN
                      dbo.employee ON dbo.SafetySuggestionsLog.Username = dbo.employee.Username LEFT OUTER JOIN
                      dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
WHERE     (dbo.employee.Username = @Username)

OR

SELECT     dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsLog.Username, ISNULL(dbo.SafetySuggestionsStatus.Status, "Not Yet") as 'Status'
FROM         dbo.SafetySuggestionsLog INNER JOIN
                      dbo.employee ON dbo.SafetySuggestionsLog.Username = dbo.employee.Username LEFT OUTER JOIN
                      dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
WHERE     (dbo.employee.Username = @Username)

答案 1 :(得分:1)

你非常正确,你可以使用ISNULL或CASE

CASE WHEN dbo.Blah.Status IS NULL THEN 'Not Yet' ELSE dbo.Blah.Status END

isnull(dbo.Blah.Status, 'Not Yet')