想象一下,我在视图中有以下SELECT语句(SQL Server 2008):
SELECT (SELECT CASE
WHEN HISTORY.OUTOFSERV = 'Y' OR HISTORY.OUTOFSERV = 'y' THEN 1
ELSE 0
END) AS OOS
FROM HISTORY
列OOS最终是int类型,但我希望它是bit类型。我怎么能做到这一点?
答案 0 :(得分:24)
使用CAST/CONVERT明确定义数据类型:
SELECT CAST (CASE
WHEN LOWER(h.outofserv) = 'y' THEN 1
ELSE 0
END AS BIT) AS OOS
FROM HISTORY h
答案 1 :(得分:4)
您应该使用CAST(1 as bit)
和CAST(0 as bit)
代替1和0:
SELECT (CASE WHEN HISTORY.OUTOFSERV = 'Y' OR HISTORY.OUTOFSERV = 'y'
THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END) AS OOS
FROM HISTORY
答案 2 :(得分:2)
这是一种获取所需BIT数据类型输出的方法,并使用更简洁的代码:
铸造()
选择CAST(CASE
当UPPER(History.OutofServ)='Y'那么1
ELSE 0
最后作为OOS
来自历史
我希望有所帮助。