0
votes

table1

contactid, LabId, date, createdby

table 2:

contactid
12
13
14
15
16

table3 Labid 4567

I would like to write sql query which inserts the data from table 2 and table 3 into Table1.

output should be like:

table1

contactid, LabId,  date,     createdby
12         4567   10/26/2018    Vish
13         4567   10/26/2018    Vish
14         4567   10/26/2018    Vish
15         4567   10/26/2018    Vish
16         4567   10/26/2018    Vish

Note: contactid and Labid are together Primary Key non-clustered. I have scenario I would like to insert into table1 only if Contactid and Labid values do not exists in table1. can any one help me with this please.

I tried below code but its not working.

If Not Exists(select * from table1 where labid in (select labid from table3 ) and contactid in (select contactid from table2)) Begin Insert into table1 (contactid, LabId, date, createdby) SELECT contactid,(select * from table3),getdate(),'Vish' FROM table2

Please help.Thank you in advance.

1
Can you post the table structure? It will be helpful to answer. And also does table3 contain contactid column? - GGadde
nope. Table_3 do not contain contactid. - Vadiya

1 Answers

0
votes

Another way, since there is only one value in table3

insert into table1 (contactid, LabId, date, createdby)
SELECT contactid,4567,'10/26/2018','Vish' 
FROM table2

Or if the value changes

Insert into table1 (contactid, LabId, date, createdby)
SELECT contactid,(select * from table3),getdate(),'Vish' 
FROM table2