在SQL Server中隐含常数1或0的位 [英] Imply bit with constant 1 or 0 in SQL Server

查看:69
本文介绍了在SQL Server中隐含常数1或0的位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在select语句中用作字段值时是否可以将1或0表示为一位?

Is it possible to express 1 or 0 as a bit when used as a field value in a select statement?

例如

在这种情况下(属于select语句的一部分),ICourseBased的类型为int.

In this case statement (which is part of a select statement) ICourseBased is of type int.

case 
when FC.CourseId is not null then 1
else 0
end
as IsCoursedBased

要使其成为位类型,我必须转换两个值.

To get it to be a bit type I have to cast both values.

case 
when FC.CourseId is not null then cast(1 as bit)
else cast(0 as bit)
end
as IsCoursedBased

是否有一种简便的方法可以将值表示为位类型而不必每次都强制转换?

Is there a short hand way of expressing the values as bit type without having to cast every time?

(我正在使用MS SQL Server 2005)

(I'm using MS SQL Server 2005)

推荐答案

cast (
  case
    when FC.CourseId is not null then 1 else 0
  end
as bit)

CAST规范为"CAST(表达式AS类型)".在这种情况下,CASE是表达式.

The CAST spec is "CAST (expression AS type)". The CASE is an expression in this context.

如果您有多个这样的表达式,我将声明vars @true和@false并使用它们.或者,如果您真的想使用UDF ...

If you have multiple such expressions, I'd declare bit vars @true and @false and use them. Or use UDFs if you really wanted...

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 Server中隐含常数1或0的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆