tags:

views:

130

answers:

4

Will it be possible to insert into two tables with same insert command?

+6  A: 

No you cannot perform multiple inserts into two tables in one query.

Anthony Forloney
+1  A: 

Maybe in a future release of MySQL you could create a View containing the 2 tables and insert into that.
But with MySQL 5.1.41 you'll get the error:
"Can not modify more than one base table through a join view"

But inserting into 2 tables with 1 query is a weird thing to do, and I don't recommend it.


For more on updatable views check out the MySQL reference.

Bob Fanger
It is not weird to want to update (or insert into) multiple tables as part of a single atomic (i.e. all or nothing happens) operation. The more normalised your database, the more likely the need. You just need to protect the multiple updates in a db transaction.
Craig Young
True, but when I see a *single* insert statement, i will assume only 1 table is affected. The "weird" part applies to the 1 query aspect.
Bob Fanger
+1  A: 

You can call a stored procedure with inserts into two tables.

recursive
+2  A: 

No you can't.

If you want to ensure the atomicity of an operation that requires data to be inserted into 2 tables, you should protect it in a transaction. You either use the SQL statements BEGIN TRAN and COMMIT TRAN, or you use a transaction boundary in whatever language you're using to develop the db access layer. E.g. something like Connection.StartTransaction and Connection.Commit (or Connection.Rollback on an error).

Craig Young