如何在T-SQL中根据列的内容输出布尔值?
我对不同表的抽象列进行了视图并对它们进行预过滤和预排序。 有一列的内容我不关心,但我需要知道内容是否为空。 因此,我的视图应该将别名传递为“true”,以防指定列的值不为 null,并传递“false”以防万一值为空。
如何使用 T-SQL 选择这样的布尔值?
I made a view to abstract columns of different tables and pre-filter and pre-sort them. There is one column whose content I don't care about but I need to know whether the content is null or not. So my view should pass an alias as "true" in case the value of this specified column isn't null and "false" in case the value is null.
How can I select such a boolean with T-SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
为此,您必须使用 CASE 语句:
You have to use a CASE statement for this:
或者你可以这样做:
Or you can do like this:
如果您需要布尔值输出
If you need a output as boolean
对于视图中的列,您可以
在声明中使用类似 或 的
内容,或者在事后进行进一步处理,我个人会使用
for the column in the view you can use something like
or in a statement
or for further processing afterwards I would personally use
我遇到了类似的问题,我希望视图根据实际列是否为空来返回布尔列类型。 我创建了一个用户定义的函数,如下所示:
然后我创建的视图返回一个位列,而不是一个整数。
I had a similar issue where I wanted a view to return a boolean column type based on if an actual column as null or not. I created a user defined function like so:
Then the view that I created returns a bit column, instead of an integer.
您要求布尔值,我们在 t-sql 中将其称为位。
其他答案要么给你一个varchar“true”和“false”,要么给你1和0。“true”和“false”显然是varchar,而不是布尔值。 我相信 1 和 0 会被转换为整数,但它肯定不是一个位。 这可能看起来很挑剔,但类型通常很重要。
要获得实际的位值,您需要将输出显式转换为类似于:
You asked for boolean, which we call bit in t-sql.
Other answers have either given you a varchar 'true' and 'false' or 1 and 0. 'true' and 'false' are obviously varchar, not boolean. I believe 1 and 0 would be cast as an integer, but it's certainly not a bit. This may seem nit-picky, but types matter quite often.
To get an actual bit value, you need to cast your output explicitly as a bit like:
我认为这比其他解决方案稍微简单一些:
SELECT Cast(ISNULL([column name], 0) AS BIT) AS IsWhatever
I think this is slightly simpler then the other solutions:
SELECT Cast(ISNULL([column name], 0) AS BIT) AS IsWhatever
从 SQL Server 2012 开始,您可以使用
IIF
Since SQL server 2012 you can use
IIF