Reputation: 466
I have a following select query:
select productid from product where productid not in (select productid from userproduct)
which gives me following output:
1
2
3
4
Now, i have another table userproduct which conatins following columns:
userid
productid
updatetime
author
I want to create following insert statements through sql:
insert into userproduct values(100,1,getdate(),'abc');
insert into userproduct values(100,2,getdate(),'abc');
insert into userproduct values(100,3,getdate(),'abc');
insert into userproduct values(100,4,getdate(),'abc');
insert into userproduct values(200,1,getdate(),'abc');
insert into userproduct values(200,2,getdate(),'abc');
insert into userproduct values(200,3,getdate(),'abc');
insert into userproduct values(200,4,getdate(),'abc');
Just for demo purpose I have used 4 values. But actually, i'll get hundreds of values. I can't create insert statements for all of them. Is there any way to create the insert statements automatically?
Upvotes: 0
Views: 153
Reputation: 987
If 100 & 200 are only two distinct userids and 'abc' is the author value always, then
insert into userproduct (userid,productid,updatetime,author)
select 100,productid,getdate(),'abc' from product where productid not in (select productid from userproduct)
Union
select 200,productid,getdate(),'abc' from product where productid not in(select productid from userproduct)
Upvotes: 1
Reputation: 5656
TRY THIS: If you have limited userid
to insert and not maintained in the table. you can use CROSS JOIN
with static userid
s as below and you can add few more if needed:
INSERT INTO userproduct (userid,productid,updatetime,author)
SELECT x.userid, p.productid, getdate(),'abc'
FROM product p
CROSS JOIN (SELECT userid FROM (values(100),(200)) x (userid)) x
WHERE productid NOT IN(SELECT productid FROM userproduct)
We can use tablename
in the CROSS JOIN
if users are maintained in any table.
Upvotes: 1
Reputation: 95101
Use an insert select statement. Cross join your results with the users table.
insert into userproduct (userid, productid, updatetime, author)
select u.userid, p.productid, getdate(), 'abc'
from product p
cross join users u
where p.productid not in (select productid from userproduct) ;
(You can of course add add criteria to restrict this to certain users, e.g. and u.userid in (100,200)
.)
(Or replace cross join users u
with cross join (select 100 as userid union all select 200) u
, if you don't want to access the users table for some reason.)
Upvotes: 1