Reputation: 2829
I need a sql statement, to insert a new row in one database table and update an existing row in another database table based on some conditions.
Is there a way to do this? To insert a row in one table and update a row in another database table in one sql statement?
Thanks in advance!
Upvotes: 1
Views: 3120
Reputation: 40884
A single SQL statement allows you to update one table, not several; if that statement is a MERGE
then you can specify insert/update/delete actions but still targeting just the same one target table.
If you just want consistency, use transactions; until a transaction is committed, changes within it are not visible to the outside world.
If you want that a single update (which you cannot control) resulted in a coordinated insert, use an on update
trigger in the table being updated. The trigger would insert appropriate row(s) into other table(s).
Upvotes: 3
Reputation: 869
Yes, it's possible with stored procedures.
Watch this: Stored procedures
Upvotes: 1
Reputation: 4935
You can use Trigger
to update second table on insert of first table
Upvotes: 1
Reputation: 26861
Yes, they are called Transactions, and are implemented with START TRANSACTION and COMMIT/ROLLBACK
with something like:
START TRANSACTION;
INSERT INTO ...
UPDATE table2 SET name='TOTO' WHERE type=1;
COMMIT;
EDIT
This is not in fact one SQL query, but the operation is done atomically - and I think that is what you need.
Upvotes: 4