在else case子句SQL中设置字段

时间:2017-10-05 08:20:42

标签: sql sql-server case-when

我想在我的视图中设置一个字段:

CREATE VIEW view AS
    SELECT
        CO AS C, 
        ErrorO AS Error,
    case
        WHEN BO IS NOT NULL THEN '1'
        ELSE ErrorO = "true"
    END AS B
FROM table;
  

' ='。

附近的语法不正确

如何将Error设置为值?

修改1

表中的一些值:

+------+------+------+-------+
|  AO  |  BO  |  Co  | ErrorO|
+------+------+------+-------+
| Data | Data | Data | false |
| Data |      | Data | false |
| Data |      | Data | true  |
+------+------+------+-------+

应输出视图的内容:

+------+-------+------+
|  C   | Error |  B   |
+------+-------+------+
| Data | false |  1   |
| Data | true  |      |
| Data | true  |      |
+------+-------+------+

4 个答案:

答案 0 :(得分:2)

SET @Error  = 
CASE WHEN A IS NOT NULL THEN '1'
    ELSE 'true' END

答案 1 :(得分:0)

SELECT title,
       CASE 
          WHEN A IS NOT NULL THEN '1'

          ELSE 'Unknown Value'
       END
FROM   tablename

答案 2 :(得分:0)

;WITH CTE AS
( SELECT *
  FROM (VALUES (1,'NOTNULL'),
               (2,NULL)
        ) AS ValuesTable(CO,AO)
)
SELECT CTE.CO AS C,
       CTE.AO AS A,
       CA.ErrorO AS Error
FROM CTE
CROSS APPLY (SELECT CASE WHEN CTE.AO IS NOT NULL THEN '1'
                         ELSE 'TRUE'
                    END AS ErrorO
            ) AS CA

答案 3 :(得分:0)

'true'为空时,您希望Error显示ErrorO而不是BO。当1不为空时,您希望显示BO而不是BO

select
  CO as C,
  case when BO is null then 'true' else ErrorO end as Error,
  case when BO is null then null else 1 end as B
from mytable;

除了BO是否为空之外的情况的替代方案:

select CO as C, 'true' as Error, null as B from mytable where BO is null
union all
select CO as C, ErrorO as Error, 1 as B from mytable where BO is not null;