使用 CASE 语句的多个条件
我需要查询一些数据。这是我构建的查询,但对我来说效果不佳。在本示例中,我使用 AdventureWorks 数据库。
SELECT * FROM [Purchasing].[Vendor] WHERE PurchasingWebServiceURL LIKE
case
// In this case I need all rows to be returned if @url is '' or 'ALL' or NULL
when (@url IS null OR @url = '' OR @url = 'ALL') then ('''%'' AND PurchasingWebServiceURL IS NULL')
//I need all records which are blank here including nulls
when (@url = 'blank') then (''''' AND PurchasingWebServiceURL IS NULL' )
//n this condition I need all record which are not like a particular value
when (@url = 'fail') then ('''%'' AND PurchasingWebServiceURL NOT LIKE ''%treyresearch%''' )
//Else Match the records which are `LIKE` the input value
else '%' + @url + '%'
end
这对我不起作用。如何在同一 CASE
的 THEN
中拥有多个 where 条件子句?我怎样才能做到这一点?
I need to query some data. here is the query that i have constructed but which isn't workig fine for me. For this example I am using AdventureWorks database.
SELECT * FROM [Purchasing].[Vendor] WHERE PurchasingWebServiceURL LIKE
case
// In this case I need all rows to be returned if @url is '' or 'ALL' or NULL
when (@url IS null OR @url = '' OR @url = 'ALL') then ('''%'' AND PurchasingWebServiceURL IS NULL')
//I need all records which are blank here including nulls
when (@url = 'blank') then (''''' AND PurchasingWebServiceURL IS NULL' )
//n this condition I need all record which are not like a particular value
when (@url = 'fail') then ('''%'' AND PurchasingWebServiceURL NOT LIKE ''%treyresearch%''' )
//Else Match the records which are `LIKE` the input value
else '%' + @url + '%'
end
This is not working for me. How can I have multiple where condition clauses in the THEN
of the the same CASE
? How can I make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是剪切和粘贴。
CASE
表达式必须返回一个值,而您返回的是一个包含 SQL 的字符串(从技术上讲,它是一个值,但类型错误)。这就是你想写的,我想:我也怀疑这可能在某些方言中不起作用,但现在无法测试(Oracle,我正在看着你),因为没有布尔值。
但是,由于
@url
不依赖于表值,为什么不进行三个不同的查询,并根据您的参数选择要评估的查询呢?It's not a cut and paste. The
CASE
expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.
However, since
@url
is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?另一种基于amadan的方式:
Another way based on amadan: