返回从SELECT查询一个布尔值 [英] Return a boolean value from a select query

查看:856
本文介绍了返回从SELECT查询一个布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想选择布尔值:

SELECT field1, field2, 1 as is_field
FROM TABLE

在Visual Studio 2010中我做的:

In Visual Studio 2010 I am doing:

bool b = row.Field<bool>("is_field");

不过,我得到异常:

But I get the exception:

指定的转换是无效的。

我怎样才能返回一个布尔值布尔,而不是 INT

How can I return a boolean value as boolean and not as int?

推荐答案

从SQL的一面,你可以这样做:

From SQL side, you can do:

SELECT field1, field2, CAST(1 AS BIT) AS is_field
FROM TABLE

要迫使它返回为位,而不是一个int。这应该做的伎俩

to force it to be returned as a BIT instead of an int. That should do the trick

更新: 什么是你的关心使用CAST这样吗? SQL Server是pretty的真棒在优化例如对于上面的查询会显示is_field的执行计划是一个常数,可以计算一次达阵(这里有一个相关文章:<一个href="http://msdn.microsoft.com/en-us/library/ms175933.aspx">http://msdn.microsoft.com/en-us/library/ms175933.aspx).即使没有,如果你关心性能,那么你不应该担心 - 这将非常有premature优化

Update: What is your concern for using CAST like this? SQL Server is pretty awesome at optimising e.g. the execution plan for above query would show is_field is a Constant which can be evaluated once up front (there's a related article here: http://msdn.microsoft.com/en-us/library/ms175933.aspx). Even without that, if you're concerned about performance, then you shouldn't worry about it - it would very much be premature optimisation.

这篇关于返回从SELECT查询一个布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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