2017-05-26 56 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;