This question already has an answer here:
How do I insert into two tables all at once in a stored procedure? [duplicate]

(1个答案)


7年前关闭。




我有2个表custlogincustinfo:
custlogin:
custid int primary key auto notnull
custusename varchar(25)
custpassword varchar(50)
custinfo:
custid foriegnkey custlogin.custid ondelete set NULL
custfirstname varchar(25)
custlastname  varchar(25)
custaddress   varchar(100)

我想写一个存储过程,它将插入到两个表中

更准确地说,使用custlogin插入custusername custpassword,这将返回custid用作custinfo的外键。

我进行了很多搜索,但未找到任何解决方案。

最佳答案

如下图所示。在这种情况下,您可以使用SCOPE_IDENTITY()来获取最后一个自动生成的ID以及此存储过程的作用域:

create procedure NameOfYourProcedureHere
as
begin
SET NOCOUNT ON;
SET XACT_ABORT ON;

    insert into custlogin(custusename, custpassword)
        values ('','') -- put values here (from parameters?)

    insert into custinfo(custid, custfirstname, custlastname, custaddress)
        values (SCOPE_IDENTITY(), '', '', '')  -- put other values here (from parameters?)

SET NOCOUNT OFF;
SET XACT_ABORT OFF;
end

08-19 09:22