![](/img/trans.png)
[英]SQL Oracle - Return message if all rows are 'None' otherwise return row. Do not return 'None'
[英]How do I make an SQL statement to return all rows when a variable is blank, otherwise return only matches
如果輸入參數為空,如何使用SQL語句返回所有行,否則僅返回匹配的行?
我的SQL看起來像這樣
where person.personstatusuid = @StatusUID
AND person.forename != ''
AND person.location = @Location
但我基本上想要person.location = @Location或@Location為空
我該怎么做? 在可能的情況下使用CASE ...
只是使用OR?
where person.personstatusuid = @StatusUID
AND person.forename != ''
AND (person.location = @Location or IsNull(@location,'')='')
SELECT *
FROM mytable
WHERE person.personstatusuid = @StatusUID
AND person.forename != ''
AND person.location = @Location
UNION ALL
SELECT *
FROM mytable
WHERE person.personstatusuid = @StatusUID
AND person.forename != ''
AND @Location IS NULL
與使用OR
不同,此解決方案對索引友好:它將優化冗余SELECT
並使用索引。
有關性能細節的類似問題,請參見我的博客中的這篇文章:
(這適用於MySQL
,但也適用於SQL Server
)
您可以使用簡單的OR條件:
where person.personstatusuid = @StatusUID
AND person.forename != ''
AND (person.location = @Location OR @Location IS NULL)
如果person.location不允許為null,則以下內容也可以工作...
where person.personstatusuid = @StatusUID
AND person.forename != ''
AND person.location = isnull(@Location,person.location)
這假定是否需要所有行,則@Location傳遞為null而不是空字符串('')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.