SQL 选择列表中的布尔表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/497522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Boolean Expressions in SQL Select list
提问by Craig Walker
I want to create a SQL Select to do a unit test in MS SQL Server 2005. The basic idea is this:
我想创建一个 SQL Select 来在 MS SQL Server 2005 中进行单元测试。基本思想是这样的:
select 'Test Name', foo = 'Result'
from bar
where baz = (some criteria)
The idea being that, if the value of the "foo" column is "Result", then I'd get a value of true/1; if it isn't, I'd get false/0.
这个想法是,如果“foo”列的值是“Result”,那么我会得到 true/1 的值;如果不是,我会得到 false/0。
Unfortunately, T-SQL doesn't like the expression; it chokes on the equals sign.
不幸的是,T-SQL 不喜欢这个表达式;它在等号上窒息。
Is there some way of evaluating an expression in the SQL select list and getting a returnable result? (Or some other way of achieving the unit testing that I want?)
是否有某种方法可以评估 SQL 选择列表中的表达式并获得可返回的结果?(或者其他一些实现我想要的单元测试的方法?)
EDIT: 3 great, answers, all built around CASE. I'll accept feihtthief's as he's got the least rep and thus needs it the most. :-) Thanks to everyone.
编辑:3 个很棒的答案,全部围绕 CASE 构建。我会接受 feihtthief 的,因为他的代表最少,因此最需要它。:-) 谢谢大家。
回答by feihtthief
Use the case construct:
使用 case 构造:
select 'Test Name',
case when foo = 'Result' then 1 else 0 end
from bar where baz = (some criteria)
Also see the MSDN Transact-SQL CASE documentation.
回答by Joel Coehoorn
SELECT 'TestName',
CASE WHEN Foo = 'Result' THEN 1 ELSE 0 END AS TestResult
FROM bar
WHERE baz = @Criteria
回答by John
Use CASE:
用例:
SELECT 'Test Name' [col1],
CASE foo
WHEN 'Result' THEN 1
ELSE 0
END AS [col2]
FROM bar
WHERE baz = (some criteria)
回答by Sebastian G
You can also use:
您还可以使用:
select
'Test Name',
iif(foo = 'Result', 1, 0)
from bar
where baz = (some criteria)
I know this was asked a while back, but I hope this helps someone out there.
我知道这是不久前被问到的,但我希望这对那里的人有所帮助。