SQL: Where MYID = ANY?

孤者浪人 提交于 2019-12-31 07:39:05

问题


In a SQL query, that contains

... WHERE MYID = @1 ....

I have to manage 2 cases
1) There is a filter on a column, @1 will be a number (1,2,X...)

2) There is no filter on that column, @1 will be ...? (ANY)

Is there something for this "any" (SQL Server 2005) ?

PS.
Obviously, I understand that I can remove the "where".

PPS.
I explain myself for better understanding: I have this query in the code, and would like to pass an integer as parameter when the filter is ON, and "something" when my filter is OFF.

if (filterOn)
    GetFoos(fooID);
else
    GetFoos("ANY");

GetFoos(param1): "select * from FOOS where FOOID = {0}", param1

回答1:


Make a UNION ALL of the two statements:

SELECT  *
FROM    mytable
WHERE   myid = @col
UNION ALL
SELECT  *
FROM    mytable
WHERE   @col IS NULL

or just split them in an IF / ELSE block of a stored procedures.

Either way, the optimizer will be able to optimize the queries separately, completely ignoring one of them depending on the value of @col.




回答2:


you could do something along this line:

 where (myid = @id or @id is null)

so you will only filter when @id contains a value and not when it is null.




回答3:


Just remove the where or and clause if there is no filter on that column.




回答4:


If you don't want to filter on a particular column, just don't filter on that column. Remove the WHERE MYID = entirely




回答5:


Having

"select * from FOO where FOOID = {0}", param

use param="FOOID" when there is no param to filter, this will give

select * from FOO where FOOID = FOOID // removing the filter


来源:https://stackoverflow.com/questions/5754619/sql-where-myid-any

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!