2017-05-26 11 views
1

嗨,我学到了sql server的BIT有真,假,未知。例如,比较1 > NULL产生unknown如何在sql server的布尔中访问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

我认为“未知”表示为NULL。 –

回答

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 
+0

谢谢你@Chuck不是你不需要放弃临时表的想法吗? –

+0

您好张,我想这只是一个最佳实践,请看这里:https://social.msdn.microsoft.com/Forums/sqlserver/en-US/522d302a-857f-4730-b49f-cca7fb236912/is- it-necessary-clean-up-drop-temporary-tables-in-stored-procedures?forum = transactsql – Chuck

+0

@YZhang,你有没有得到这个工作? – Chuck

0

你需要有IS NULL谓词CASE表达式返回字符串“未知”作为最后一列值,这也需要其他'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;