SQL Server存储过程在多个表中插入一个

SQL Server存储过程在多个表中插入一个

问题描述:

我有2个表,custlogincustinfoSQL Server存储过程在多个表中插入一个

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) 

我想写一个存储将插入到两个表中的程序

更精确使用custusername custpassword插入custlogin,它将返回custid用作custinfo的外键。

我已经搜索了很多,但我没有找到任何解决方案。

它会像下面这样。您可以使用SCOPE_IDENTITY()得到最后自动生成的ID withing这是在这种情况下,这个存储过程范围:

create procedure NameOfYourProcedureHere 
as 
begin 

    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?) 

end 
+0

你对你自己的问题回答1分钟后,因为有人问?嗯...闻起来有点不对劲 – anatol

如果插入1行custlogin,你可以使用@@IDENTITYScope_identity(),以获得新插入的ID。

如果您插入多行,则使用OUTPUT来获取多个新插入的ID。

你可以在这里看到一个例子:http://rextester.com/TWXO81648

+0

我建议使用** SCOPE_IDENTITY()**代替其他任何东西来抓取新插入的身份值。 [请参阅此博客文章,了解有关WHY的解释](http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity -of-record /) –

+0

谢谢@marc_s,..... – TriV