如何在sql server的布尔值中访问UNKNOWN?

时间:2017-05-26 22:06:06

标签: sql sql-server null boolean bit

您好我知道sql server的BIT有true,false和unknown。例如,比较1 > NULL会产生unknown

我知道我可以间接检查:如果x is null or y is null,那么比较x > y必须是unknown

有没有办法直接访问unknown?例如

select *
into #t
from (
    SELECT 1 as [x], 1 as [y] UNION ALL
    SELECT 1 as [x], 2 as [y] UNION ALL
    SELECT 1 as [x], NULL as [y]
) as a


SELECT *
from #t
--x y
--1 1
--1 2
--1 NULL

select *
    ,/* ???? */ as [is x > y]
from #t
--want to have:
--x y      is x > y
--1 1      0
--1 2      0
--1 NULL   unknown

2 个答案:

答案 0 :(得分:1)

这将有效:

select *
into #t
from (
    SELECT 1 as [x], 1 as [y] UNION ALL
    SELECT 1 as [x], 2 as [y] UNION ALL
    SELECT 1 as [x], NULL as [y]
) as a


SELECT *
from #t
--x y
--1 1
--1 2
--1 NULL

select *,
    case  
        when x > y then '1' 
        when x is null or y is null then 'unknown'
        else '0' 
        end as [is x > y]
from #t

--x y    is x > y
--1 1    0
--1 2    0
--1 NULL unknown

-- Don't forget to delete your temp table when done. 
drop table  #t 

答案 1 :(得分:0)

您需要一个带有CASE谓词的IS NULL表达式,以将字符串'unknown'作为最后一列值返回,这也需要其他'0'和'1'值作为varchar文字以避免将“未知”字符串文字隐式转换为int。

SELECT
      x
    , y
    , CASE WHEN x > y THEN '1' WHEN x <= y THEN '0' ELSE 'unknown' END AS [is x > y]
FROM #t;