Ted
Ted

Reputation: 1760

Some kind of IF condition in INSERT

I have next tables:

   table1               table2
id. value position    id   state
                       1.  false

What I need is to insert data in to table1 if state from table2 is true. Something like:

INSERT INTO table1(value, position)
VALUES('someVal', 3)
IF table2.id = 1 AND table2.state = true

Upvotes: 0

Views: 32

Answers (2)

Karlheim
Karlheim

Reputation: 121

You can select only item where table2.State = true before inserting

If you have your data comming from another table it would look like this

INSERT INTO table1(value, position)
SELECT ValueId, Value 
FROM TableValue
INNER JOIN Table2
ON TableValue.ValueID = Table2.ID
WHERE table2.state = true

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1270411

Do you want exists?

INSERT INTO table1(value, position)
    SELECT v.value, v.position
    FROM (VALUES('someVal', 3)) v(value, position)
    WHERE EXISTS (SELECT 1 FROM TABLE2 t2 WHERE t2.id = 1 AND t2.state = true);

Upvotes: 2

Related Questions