两张表关联如何实现同时插入数据 sql具体语句

来源:互联网 发布:百姓网发帖软件 编辑:程序博客网 时间:2024/06/06 12:25
这样的语句可以放在存储过程里
declare @id int
insert into table1 (name,password) values (...)
set @id=@@identity --取到刚插入的id
insert into table2 (age,sex,userid) values (...@id)

其实这样就可以了。如果你担心两个表的数据不同步,比如可能插入了table1后,但是出错了,表1有数据但表2没有,你可以把这2条语句放一个事务里。

本例主要应用了sql server @@identiy 获取刚刚插入的语句自增主键字段