Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select literals as table data in SQL server

Consider table Address , with fields Country, State, and other data fields. I want to get all the records except for those with Country,State combination as (US, IL), (US,LA), (IND,DEL)

The query goes like

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
)

How can it be easily achieved (to replace coutry,state combination of union with simple subquery)? As total data is not very large, i am least bothered about performance for now.


I know i can create table variable, add all literal combination there using insert into syntax, and use table variable for not exists, but i feel it is overkill for small requirement (not exists on 2 variables).

like image 305
Tilak Avatar asked Nov 14 '13 17:11

Tilak


3 Answers

Looks like your query tried to do this:

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
                 )

Or you could not use a derived table and still get the same result

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'
          )
like image 109
Mikael Eriksson Avatar answered Oct 26 '22 06:10

Mikael Eriksson


Simply use the values directly in the query:

-- 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;
like image 28
HABO Avatar answered Oct 26 '22 06:10

HABO


or

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;
like image 34
ARA Avatar answered Oct 26 '22 08:10

ARA