在 select 语句中用作字段值时,是否可以将 1 或 0 表示为一个位?
例如
在本例中,语句(它是 select 语句的一部分)ICourseBased 的类型为 int。
case
when FC.CourseId is not null then 1
else 0
end
as IsCoursedBased
为了使其成为位类型,我必须转换这两个值。
case
when FC.CourseId is not null then cast(1 as bit)
else cast(0 as bit)
end
as IsCoursedBased
是否有一种简便的方法可以将值表示为位类型,而不必每次都进行强制转换?
(我使用的是 MS SQL Server 2005)
最佳答案
cast (
case
when FC.CourseId is not null then 1 else 0
end
as bit)
CAST 规范是“CAST(表达式 AS 类型)”。在这种情况下,CASE 是一个表达式。
如果你有多个这样的表达式,我会声明位变量@true和@false并使用它们。或者如果您确实想要的话,可以使用 UDF...
DECLARE @True bit, @False bit;
SELECT @True = 1, @False = 0; --can be combined with declare in SQL 2008
SELECT
case when FC.CourseId is not null then @True ELSE @False END AS ...
关于sql - 在 SQL Server 中用常量 1 或 0 暗示位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1172795/