如何使用 T-SQL 的 Case/When?
我有一个巨大的查询,经常使用case/when。现在我这里有这个SQL,它不起作用。
(select case when xyz.something = 1
then
'SOMETEXT'
else
(select case when xyz.somethingelse = 1)
then
'SOMEOTHERTEXT'
end)
(select case when xyz.somethingelseagain = 2)
then
'SOMEOTHERTEXTGOESHERE'
end)
end) [ColumnName],
造成问题的是 xyz.somethingelseagain = 2,它表示无法绑定该表达式。 xyz 是在查询中进一步连接的表的一些别名。这里出了什么问题?删除 2 个案例/时间之一可以纠正这一问题,但我需要这两个案例,甚至可能需要更多案例。
I have a huge query which uses case/when often. Now I have this SQL here, which does not work.
(select case when xyz.something = 1
then
'SOMETEXT'
else
(select case when xyz.somethingelse = 1)
then
'SOMEOTHERTEXT'
end)
(select case when xyz.somethingelseagain = 2)
then
'SOMEOTHERTEXTGOESHERE'
end)
end) [ColumnName],
Whats causing trouble is xyz.somethingelseagain = 2
, it says it could not bind that expression. xyz is some alias for a table which is joined further down in the query. Whats wrong here? Removing one of the 2 case/whens corrects that, but I need both of them, probably even more cases.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一旦 WHEN 语句为 true,中断就会隐式发生。
您必须考虑哪个 WHEN 表达式最有可能发生。如果您将 WHEN 放在一长串 WHEN 语句的末尾,您的 sql 可能会变慢。所以把它放在前面作为第一个。
更多信息请参见:T-SQL 中的 case 语句中的中断
As soon as a WHEN statement is true the break is implicit.
You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.
More information here: break in case statement in T-SQL
如果逻辑测试针对单个列,那么您可以使用类似
更多信息 - https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql -服务器-2017
If logical test is against a single column then you could use something like
More information - https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017