我想同时在两个表中插入数据 [英] I want to insert data in two tables at same time

查看:95
本文介绍了我想同时在两个表中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表,并且同时在两个表中插入数据,但是一个表包含自动生成的数字,并且自动生成的数字插入到第二个表中.

谢谢

I have two tables and insert data in both tables at same time but one table contains autogenerated numbers and autogenerated numbers insert into 2nd table.

Thanks

推荐答案

假设您有一个正在调用的存储过程,
并且您正在使用TSQl:

宣告@AutoGeneratedId int

INSERT INTO table1
(a,b,c)

(1,2,3)

SET @AutoGeneratedId = SCOPE_IDENTITY();


INSERT INTO table2
(fkFromTable1,q,w)
(@AutoGeneratedId,4,5)
Assuming you have a stored procedure that you are calling,
and that you are using TSQl:

DECLARE @AutoGeneratedId int

INSERT INTO table1
(a,b,c)
values
(1,2,3)

SET @AutoGeneratedId = SCOPE_IDENTITY();


INSERT INTO table2
(fkFromTable1,q,w)
(@AutoGeneratedId, 4,5)


如果您要处理具有公共ID的数据,那么自动生成的数字不一定是要走的路.您将必须将该项目插入一个表中,然后再将其选中以找出分配的编号,然后将其添加到第二个表中.
查看使用Guid代替-因为您分配的是Guid,而不是数据库,因此在这种情况下它会更好地工作.此外,如果以后需要复制,它将使复制更加容易.
If you are dealing with data which has a common id, then automatically generated numbers are not necessarily the way to go. You would have to insert the item in one table, then select it back to find out the number assigned, then add it to the second table.
Look at using a Guid instead - since you assign it rather than the database, it works better in such circumstances. Additionally, it makes replication easier if you need that later.


插入1个表中.
然后
Insert into 1 table.
Then
SELECT MAX(ID) FROM TABLENAME


将此ID存储在变量&中.然后只需将其插入到另一个表中即可.

它是有史以来最好,最准确的代码.
干杯...


Store this ID in variable & then simply insert it to another table.

Its the best and more accurate code ever seen.
Cheers...


这篇关于我想同时在两个表中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆