运行时从查询中更改值

时间:2016-11-16 13:55:44

标签: sql

SELECT 
    'https://xxxxxx/' + CONVERT(VARCHAR(10), [AnnouncementID]) AS 'URL', 
    [Status] AS 'Code', 
    [Subject] AS 'Text', 
    (CASE 
        WHEN LEN([Subject]) > 500 
           THEN SUBSTRING([Subject], 0, 500) + '...' 
           ELSE [Subject] END) 
    AS 'ShortText'
FROM 
    [Announcement] 
WHERE 
    [Public] = 1 
    AND [Enable] = 1 
    AND GETDATE() BETWEEN [ActiveFrom] AND [ActiveTo] 
ORDER BY 
    [Status] ASC, [ActiveFrom] ASC

此查询返回类似于:

的内容
Url                 Code        Text    ShortText
-------------------------------------------------
https://xxxxxx/2    Enable      Text    Text
https://xxxxxx/1    Critical    Text    Text

我想自动更改[Code]中的文字。

  • 如果严重 - > RED
  • 如果已启用 - > YELLOW

如何在上面重写我的查询字符串?

3 个答案:

答案 0 :(得分:1)

使用CASE:

CASE [Status]
    WHEN 'Enable' then 'YELLOW'
    WHEN 'Critical'  then 'RED'
END as 'Code'

或使用带有值的JOINED表。

答案 1 :(得分:0)

如果我理解正确;你想分别将单词Enable和Critical改为YELLOW和RED吗?

您可以使用案例陈述执行此操作,因为您还没有标记您正在使用的DBMS,但我可以对语法提供帮助,但粗略的想法会是这样;

SELECT 'https://xxxxxx/' + CONVERT(VARCHAR(10), [AnnouncementID]) AS 'URL', 
Case [Status]
  when 'Critical' then 'RED'
  when 'Enable' then 'YELLOW'
  end AS 'Code' , 
[Subject] AS 'Text', 
(CASE WHEN LEN([Subject]) > 500 THEN SUBSTRING([Subject], 0, 500) + '...' ELSE [Subject] END) AS 'ShortText' 

FROM [Announcement] 

WHERE [Public] = 1 
AND [Enable] = 1 
AND GETDATE() BETWEEN [ActiveFrom] AND [ActiveTo] 

ORDER BY [Status] ASC, [ActiveFrom] ASC

它是否有效地说明[状态]是否具有“关键”的价值'显示' RED'或者如果有值'启用'然后显示' YELLOW'

答案 2 :(得分:0)

结帐this answer。它引用了this article。 通过一些小修改,根据[代码]的值添加一些CASE语句,您可以添加<td style="color: red;"><td style="color: yellow;">

我希望有所帮助!