views:

41

answers:

4

how do i get this result into a new table?

SELECT DISTINCT h.CustomerCode, h.BillName, h.BillAddress1
FROM hist2 h
WHERE NOT EXISTS
       (SELECT CustomerCode FROM tblCustomer c WHERE c.CustomerCode = h.CustomerCode)
A: 

This works on most SQLs—I'm not sure of MS:

create table tablename
  select Distinct h.CustomerCode, h.BillName, h.BillAddress1
  From hist2 h
  where not exists (select CustomerCode
                     From tblCustomer c
                     Where c.CustomerCode=h.CustomerCode)
wallyk
+1  A: 

Like this:

SELECT DISTINCT h.CustomerCode, h.BillName, h.BillAddress1
INTO NewTable
FROM hist2 h
WHERE NOT EXISTS
   (SELECT CustomerCode FROM tblCustomer c WHERE c.CustomerCode = h.CustomerCode)
RBarryYoung
+1  A: 

if a table exists that matches your fields:

insert into mytable
   select Distinct h.CustomerCode, h.BillName, h.BillAddress1 From hist2 h where not exists (select CustomerCode From tblCustomer c Where c.CustomerCode=h.CustomerCode)

if it doesn't match your fields, you have to specify fields, as in all inserts:

insert into mytable (customercode, billname...)
    select Distinct h.CustomerCode, h.BillName, h.BillAddress1 From hist2 h where not exists (select CustomerCode From tblCustomer c Where c.CustomerCode=h.CustomerCode)

if the table doesn't exist, you want to use Select Into

David Hedlund
A: 

If you don't have a table already, e.g. you want to store it into a brand new table, you can use this syntax here:

SELECT DISTINCT h.CustomerCode, h.BillName, h.BillAddress1
INTO dbo.NewTable
FROM hist2 h
WHERE NOT EXISTS
       (SELECT CustomerCode FROM tblCustomer c WHERE c.CustomerCode = h.CustomerCode)

Just add the "INTO (tablename)" clause - that's all there is!

marc_s
Doesn't `INTO` require that the table already exist?
wallyk
NO, on the contrary - if the target table already exists, it will terminate the statement and not to anything.
marc_s