2013-11-14 51 views
0

考慮表格地址,其中包含Country,State和其他數據字段。我想除了那些與國家,國家組合(美國,IL),(美國洛杉磯),(IND,DEL)選擇文字作爲SQL服務器中的表格數據

查詢是這樣

Select * from Address a 
where not exists 
(
    select Country,State 
    (select 'US' as Country, 'IL' as State 
    union 
    select 'US' as Country, 'LA' as State 
    union 
    select 'IND' as Country, 'DEL' as State 
) e 
where e.Country != a.Country and e.State != a.state 
) 

如何能夠記錄它很容易實現(取代coutry,聯合與簡單子查詢的狀態組合)?由於總體數據不是很大,我現在對性能影響最小。


我知道我可以在那裏創建表變量,添加所有文字組合使用INSERT INTO語法,並使用表變量不存在,但我覺得這是矯枉過正小的要求(不存在於兩個變量)。

+0

請說明您的具體問題或添加其他詳細信息,以確切地突出顯示您的需求。正如目前所寫,很難確切地說出你在問什麼。 – Kermit

+0

我會添加一個例子來更好地說明這個問題 – Tilak

+0

這聽起來像你問我如何創建動態SQL,或者B)在這個特定情況下編寫更優化的SQL - 可以使用更好的問題描述 –

回答

4

看起來你的查詢試圖做到這一點:

select * 
from Address a 
where not exists (
       select * 
       from (
         select 'US' as Country, 'IL' as State union all 
         select 'US' as Country, 'LA' as State union all 
         select 'IND' as Country, 'DEL' as State 
        ) e 
       where e.Country = a.Country and 
         e.State = a.State 
       ) 

或者你不能使用派生表,仍然得到同樣的結果

select * 
from Address as a 
where not (
      a.Country = 'US' and a.State = 'IL' or 
      a.Country = 'US' and a.State = 'LA' or 
      a.Country = 'IND' and a.State = 'DEL' 
     ) 
0

只需直接在查詢中使用的值:

-- Sample data. 
declare @Table as Table (Country VarChar(6), State VarChar(6), Foo VarChar(6)); 
insert into @Table (Country, State, Foo) values 
    ('US', 'IL', 'one'), ('XX', 'LA', 'two'), ('IND', 'XXX', 'three'), ('IND', 'DEL', 'four'); 

select * from @Table; 

-- Demonstrate excluding specific combinations. 
select T.* 
    from @Table as T left outer join 
    (values ('US', 'IL'), ('US', 'LA'), ('IND', 'DEL')) as Exclude(Country, State) 
    on T.Country = Exclude.Country and T.State = Exclude.State 
    where Exclude.Country is NULL; 
1

select * 
from Address a 
left outer join 
    (select 'US' as Country, 'IL' as State 
     union select 'US', 'LA' 
     union select 'IND', 'DEL' ) as n 
    on a.Country = n.Country and a.State = n.State 
    where n.Country is NULL; 
相關問題