Reputation: 15245
I'd like to insert a row into table A, but only if another row in table B exists. For example something like this...
IF EXISTS (SELECT * FROM B WHERE id=1)
INSERT INTO A
(id, value1, value2)
VALUES (1, 'foo', 'bar')
However that doesn't work. What will?
Upvotes: 0
Views: 418
Reputation: 10402
INSERT INTO A (value1, value2, value3)
SELECT 'foo', 'bar', 'foo' FROM B WHERE ID = 1
One potential problem here is if your condition is met more than once it will insert as many rows so adjust your query to that, but it will do what you want, only insert if the conditions on the select are met.
Upvotes: 3