Tomas H Tomas H - 1 month ago 6
SQL Question

Inserting result of query in existing table

Hi my table zadavatel has following structure

enter image description here

when I run a query on new data I get some new entries for zadavatel field.This basically gets new zadavatel entries which are not present in former table

select distinct zadavatel from [dbo].[DATA_2016_CZ]
where zadavatel not in (select zadavatel from zadavatel)


I need to get this entries into this table, the field advertiser should be for this new entries exact copy of zadavatel field and the value for NOTE should be 2.

if the output of query is like this

enter image description here

then I want to add to my table

zadavatel advertiser note
Al Namura Al Namura 2


and so on for all entries

Can you advise on the query ?

thanks

vkp vkp
Answer

You can use insert into..select to do this.

insert into zadavatel (zadavatel, advertiser, note)
select distinct zadavatel , zadavatel, 2
from [dbo].[DATA_2016_CZ] 
where zadavatel not in (select zadavatel from zadavatel)

Or

insert into zadavatel (zadavatel, advertiser, note)
select distinct zadavatel , zadavatel, 2
from [dbo].[DATA_2016_CZ] d
where not exists (select 1 from zadavatel where zadavatel=d.zadavatel)