存储过程(将数据插入表中,然后将生成的id插入另一个)SQL Server

时间:2022-11-25 10:23:28

I want to insert data into table 1, then I want to insert the generated idAddress into table 2, how can I do this?

我想将数据插入表1,然后我想将生成的idAddress插入表2,我该怎么做?

Table 1 PK-idAddress, street, cp

表1 PK-idAddress,street,cp

Table 2 PK-idUser, FK-idAddress,

表2 PK-idUser,FK-idAddress,

Thanks in advance.

提前致谢。

1 个解决方案

#1


2  

Try this out:

试试这个:

INSERT INTO table1(STREET, CP) VALUES('THIS', 'THAT')
INSERT INTO table2(FK-IDADDRESS) VALUES(@@IDENTITY) -- OR SCOPE_IDENTITY

Well, since I'm not sure of your tables structure and of your full code, that's just an assumption up there (my code, I mean) -- Basically, it's calling @@IDENTITY or SCOPE_IDENTITY -- read into the links below to get an idea of what you might really need.

好吧,因为我不确定你的表结构和完整的代码,这只是一个假设(我的代码,我的意思) - 基本上,它调用@@ IDENTITY或SCOPE_IDENTITY - 读入下面的链接了解您可能真正需要的东西。

SCOPE_IDENTITY

@@IDENTITY

DIFFERENCE BETWEEN...

There's another method you can use:

您可以使用另一种方法:

IDENT_CURRENT

And you can read this too:

你也可以读这个:

http://sqlserverpedia.com/wiki/Functions_-_@@IDENTITY,_SCOPE_IDENTITY,_IDENT_CURRENT

*credit goes to @JakeFeasel for bringing up IDENT_CURRENT

*赠送给@JakeFeasel以提出IDENT_CURRENT

#1


2  

Try this out:

试试这个:

INSERT INTO table1(STREET, CP) VALUES('THIS', 'THAT')
INSERT INTO table2(FK-IDADDRESS) VALUES(@@IDENTITY) -- OR SCOPE_IDENTITY

Well, since I'm not sure of your tables structure and of your full code, that's just an assumption up there (my code, I mean) -- Basically, it's calling @@IDENTITY or SCOPE_IDENTITY -- read into the links below to get an idea of what you might really need.

好吧,因为我不确定你的表结构和完整的代码,这只是一个假设(我的代码,我的意思) - 基本上,它调用@@ IDENTITY或SCOPE_IDENTITY - 读入下面的链接了解您可能真正需要的东西。

SCOPE_IDENTITY

@@IDENTITY

DIFFERENCE BETWEEN...

There's another method you can use:

您可以使用另一种方法:

IDENT_CURRENT

And you can read this too:

你也可以读这个:

http://sqlserverpedia.com/wiki/Functions_-_@@IDENTITY,_SCOPE_IDENTITY,_IDENT_CURRENT

*credit goes to @JakeFeasel for bringing up IDENT_CURRENT

*赠送给@JakeFeasel以提出IDENT_CURRENT