2013-11-14 33 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; 
相关问题