2017-05-05 130 views
1

我有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的外鍵。

我已經搜索了很多,但我沒有找到任何解決方案。

回答

0

它會像下面這樣。您可以使用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

0

如果插入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

相關問題