SQL 选择列表中的布尔表达式

发布于 2024-07-13 04:10:50 字数 469 浏览 8 评论 0原文

我想创建一个 SQL Select 来在 MS SQL Server 2005 中进行单元测试。基本思想是这样的:

select 'Test Name', foo = 'Result'
from bar
where baz = (some criteria)

这个思想是,如果“foo”列的值为“Result”,那么我会得到一个值真/1; 如果不是,我会得到 false/0。

不幸的是,T-SQL 不喜欢这个表达式; 它因等号而窒息。

是否有某种方法可以计算 SQL 选择列表中的表达式并获得可返回的结果? (或者实现我想要的单元测试的其他方式?)


编辑:3 个很棒的答案,全部围绕 CASE 构建。 我会接受 feihtthief 的,因为他的代表最少,因此最需要它。 :-) 谢谢大家。

I want to create a SQL Select to do a unit test in MS SQL Server 2005. The basic idea is this:

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.

Unfortunately, T-SQL doesn't like the expression; it chokes on the equals sign.

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?)


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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你是我的挚爱i 2024-07-20 04:10:50

使用 case 构造:

select 'Test Name', 
    case when foo = 'Result' then 1 else 0 end 
    from bar where baz = (some criteria)

另请参阅MSDN Transact-SQL CASE 文档

Use the case construct:

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.

凉栀 2024-07-20 04:10:50
SELECT 'TestName', 
    CASE WHEN Foo = 'Result' THEN 1 ELSE 0 END AS TestResult
FROM bar 
WHERE baz = @Criteria
SELECT 'TestName', 
    CASE WHEN Foo = 'Result' THEN 1 ELSE 0 END AS TestResult
FROM bar 
WHERE baz = @Criteria
梦与时光遇 2024-07-20 04:10:50

使用案例:

SELECT 'Test Name' [col1],
  CASE foo
    WHEN 'Result' THEN 1
    ELSE 0
  END AS [col2]
FROM bar
WHERE baz = (some criteria)

Use CASE:

SELECT 'Test Name' [col1],
  CASE foo
    WHEN 'Result' THEN 1
    ELSE 0
  END AS [col2]
FROM bar
WHERE baz = (some criteria)
英雄似剑 2024-07-20 04:10:50

您还可以使用:

select 
    'Test Name', 
    iif(foo = 'Result', 1, 0)
from bar 
where baz = (some criteria)

我知道不久前有人问过这个问题,但我希望这对那里的人有帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文