选择文本作为SQL server中的表数据

选择文本作为SQL server中的表数据,sql,sql-server,tsql,where-clause,Sql,Sql Server,Tsql,Where Clause,考虑表地址,包括国家、州和其他数据字段。我想得到所有的记录,除了那些国家,州的组合,如美国,伊利诺伊州,美国,洛杉矶,印第安纳州,德尔 查询结果如下 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 unio

考虑表地址,包括国家、州和其他数据字段。我想得到所有的记录,除了那些国家,州的组合,如美国,伊利诺伊州,美国,洛杉矶,印第安纳州,德尔

查询结果如下

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
)
如何轻松地用简单的子查询替换联合的状态组合?由于总数据不是很大,我现在最不担心性能


我知道我可以创建表变量,使用insert将所有文字组合添加到语法中,并将表变量用于not exists,但我觉得对于2个变量上不存在的小要求来说,这太过分了。

看起来您的查询试图这样做:

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'
          )

只需在查询中直接使用这些值:

-- 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;


请澄清您的具体问题或添加其他详细信息,以突出显示您所需的内容。正如目前所写的,很难说清楚你在问什么。我将添加一个例子来说明这个问题。我觉得你在问如何创建动态SQL,或者在这种情况下编写更优化的SQL—可以更好地描述问题这似乎让人困惑,因为您有一个填充了国家和州列的表,并且您正在执行一个“不存在”来从中选择数据。在Country=@Country和State=@State的地址中选择*有什么问题?您的示例有3个国家/州对。3是一个固定的数字。如何获得3对-特别是通过传递的参数或作为查询结果?
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;