SQL if else 子句中可以有 select 吗?

发布于 2024-12-18 16:05:44 字数 420 浏览 1 评论 0原文

我怀疑这是可能的,但就这样吧。

我需要制定一个 SQL 查询(绝对不允许使用存储过程)来执行如下操作:

Select A.valueFromTable -B.ValueFromTable As result
From table as A inner join table as B
on A.ValueID = B.ValueID
Where ValueID =5

但我需要条件:

if (result <0)
Begin
select A As result ....
end
else
select A-B as result ...

任何帮助将不胜感激,即使它确认它无法完成。

通过搜索,我相信我当前使用的 SQL Server 版本是 8.0

I doubt this is possible but here goes.

I need to formulate a SQL query (absolutely not allowed a stored procedure) that does something like this:

Select A.valueFromTable -B.ValueFromTable As result
From table as A inner join table as B
on A.ValueID = B.ValueID
Where ValueID =5

But I need the condition:

if (result <0)
Begin
select A As result ....
end
else
select A-B as result ...

Any help would be greatly appreciated even if it's confirming that it cannot be done.

From searches I believe the version of SQL Server I am currently using is 8.0

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

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

发布评论

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

评论(4

巴黎盛开的樱花 2024-12-25 16:05:44
Select 
    CASE
        WHEN A.valueFromTable -B.ValueFromTable < 0 THEN A.valueFromTable 
    ELSE A.valueFromTable -B.ValueFromTable END As result
From table as A inner join table as B
on A.ValueID = B.ValueID
Where ValueID =5
Select 
    CASE
        WHEN A.valueFromTable -B.ValueFromTable < 0 THEN A.valueFromTable 
    ELSE A.valueFromTable -B.ValueFromTable END As result
From table as A inner join table as B
on A.ValueID = B.ValueID
Where ValueID =5
骑趴 2024-12-25 16:05:44

使用 CASE 语句:

SELECT CASE WHEN A-B < 0 THEN A ELSE A-B END AS result

Use a CASE statement:

SELECT CASE WHEN A-B < 0 THEN A ELSE A-B END AS result
何时共饮酒 2024-12-25 16:05:44

您正在寻找 SQL CASE声明。

select
    case when (A-B < 0)
        then A
    else A-B
    end as result
from
    ...

You are looking for the SQL CASE statement.

select
    case when (A-B < 0)
        then A
    else A-B
    end as result
from
    ...
妖妓 2024-12-25 16:05:44

我非常有信心您可以使用 IF 条件找到解决方案,但如果其他所有方法都失败,也许可以尝试真正混淆的方法: SELECT (A.valueFromTable - (result < 0) * B.ValueFromTable)

这依赖于错误条件评估零。

I'm pretty confident that you can find a solution using IF conditionals, but if all else fails perhaps try the really obfuscated: SELECT (A.valueFromTable - (result < 0) * B.ValueFromTable)

This relies on false conditions evaluating to zero.

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