TSQL条件IN子句

时间:2014-08-07 00:54:02

标签: sql-server-2008 tsql

我想像我一样在我的专栏上查找...

Where [Location 1] IN(@Brooklyn , @Queens)

但是如果指定NO LOCATION我想做这样的事情......

Where [Location 1]  = [Location 1]

换句话说,如果没有指定位置,我想返回所有行。

这是我到目前为止所尝试过的。它有效......必须有更好的方法。

Declare @Queens varchar(100)
Set @Queens = 'Queens'
Declare @Brooklyn varchar(100)
Set @Brooklyn = 'Brooklyn'

select * from AIDE_AVAILABILITY_REPORT 
where 
(
[LOCATION 1] = (Case When @Brooklyn is Not NULL Then 'Brooklyn' End) OR
[LOCATION 2] = (Case When @Brooklyn is Not NULL Then 'Brooklyn' End) OR

[LOCATION 1] = (Case When @Brooklyn is Null Then [LOCATION 1] End) OR
[LOCATION 2] = (Case When @Brooklyn is Null Then [LOCATION 2] End)

)
AND
(
[LOCATION 1] = (Case When @Queens is Not NULL Then 'Queens' End) OR
[LOCATION 2] = (Case When @Queens is Not NULL Then 'Queens' End) OR

[LOCATION 1] = (Case When @Queens is Null Then [LOCATION 1] End) OR
[LOCATION 2] = (Case When @Queens is Null Then [LOCATION 2] End)
)

3 个答案:

答案 0 :(得分:2)

您可能需要考虑这种方法:

if object_id('Locations') is not null drop table Locations

Create table Locations 
(
    location nvarchar(100) 
)

insert into Locations values('Brooklyn')
insert into Locations values('Queens')
insert into Locations values('Manhattan')
insert into Locations values('Bronx')
insert into Locations values('Staten Island')


Declare @locationlookup table 
(
    location nvarchar(100)
)

Declare @locations nvarchar(max)
Set @locations = ',Brooklyn,Queens,' 

if @locations <> '' 
    insert into @locationlookup 
        select location 
            from Locations 
                        where charindex(',' + location + ',', @locations) > 0  
else 
    insert into @locationlookup select location from Locations

select * from 
    AIDE_AVAILABILITY_REPORT a, @locationlookup b  
    where 
        a.location1 = b.location
        OR a.location2 = b.location         

答案 1 :(得分:1)

CASE表达式中,请务必使用ELSE部分,而不是将其默认为NULL。这将为每组保存一行:

where 
(
[LOCATION 1] = (Case When @Brooklyn is Not NULL Then 'Brooklyn' ELSE [LOCATION 1] End) OR
[LOCATION 2] = (Case When @Brooklyn is Not NULL Then 'Brooklyn' ELSE [LOCATION 2] End)
)
AND
(
[LOCATION 1] = (Case When @Queens is Not NULL Then 'Queens' ELSE [LOCATION 1] End) OR
[LOCATION 2] = (Case When @Queens is Not NULL Then 'Queens' ELSE [LOCATION 2] End)
)

我会重新考虑你的变量。而不是在每个行政区之后命名变量,或许有一个带有自治市镇名称的变量会更好:

WHERE [LOCATION 1] = (CASE WHEN @borough IS NULL THEN [LOCATION 1] ELSE @borough END) OR
      [LOCATION 2] = (CASE WHEN @borough IS NULL THEN [LOCATION 2] ELSE @borough END)

答案 2 :(得分:0)

每当我看到这种问题时,我就像这样使用ISNULL:

SELECT * FROM AIDE_AVAILABILITY_REPORT 
WHERE ISNULL([Location 1],@Brooklyn) IN (@Brooklyn,@Queens) 
   OR ISNULL([Location 2],@Brooklyn) IN (@Brooklyn,@Queens) 

但是你似乎认为变量可能为null(给出你的例子),我会这样做:

SELECT * FROM AIDE_AVAILABILITY_REPORT 
WHERE [Location 1] IN (ISNULL(@Brooklyn,[Location 1],ISNULL(@Queens,[Location 1])
   OR [Location 2] IN (ISNULL(@Brooklyn,[Location 1],ISNULL(@Queens,[Location 1])