[英]how to write more than one insert statements in stored procedure with two table parameters
我有兩張桌子
Employee---->Id(identity),FN,LN,Address
EmpContact--->Id(identity),Empid(Above table identity value),ContactType,ContactNumber
如何在單個存儲過程中編寫兩個表插入語句。 第二個表“EmpContact”需要插入第一個表“Employee”的結果標識 ID
您需要的是 SCOPE_IDENTITY() 函數,它返回范圍內的最后一個 ID
insert into Employee(FN,LN, Adress)
values(@var1, @var2, @var3)
declare @EmpID int
set @EmpID = SCOPE_IDENTITY()
insert into EmpContact(Empid, ContactType, contactNumber)
values(@EmpID, @var4, @var5)
emmm... 答案很簡單,只要寫一個帶有錯誤處理等的程序就可以了。
create procedure dbo.myProc
@param
insert into dbo.Employee(FN,LN,Address)
select @value1, @value2, @value3
insert into dbo.EmpContact(Empid,ContactType,ContactNumber)
select ID,@value4, @value5
from dbo.Employee
go
假設您的未知字段作為參數傳入:
在您的存儲過程中...
DECLARE @EmployeeID BIGINT --Or whatever datatype you are using
INSERT INTO Employee
(FN, LN, Address)
VALUES
(@FN, @LN, @Address)
SET @EmployeeID = SCOPE_IDENTITY() --This is probably the line you are looking for
INSERT INTO EmpContact
(Empid, ContractType, ContractNumber)
VALUES
(@EmployeeID, @ContractType, @ContractNumber)
create proc yourproc
(
-- parameter definitions here
)
as
begin
insert into Employee
(FN,LN,Address)
values
(@FN,@LN,@Address)
declare @EmployeeID int
set @EmployeeID = SCOPE_IDENTITY()
insert into EmpContact
(Empid, ContactType, ContactNumber)
values
(@EmployeeID, @ContactType, @ContactNumber)
end
SCOPE_IDENTITY 和@@IDENTITY 返回在當前會話的任何表中生成的最后一個標識值。 但是,SCOPE_IDENTITY 返回僅在當前范圍內插入的值; @@IDENTITY 不限於特定范圍。
您可以使用原始插入內容,但您可以使用第一個表中插入的身份 ID SCOPE_IDENTITY()
,它返回為當前會話和當前范圍中的任何表生成的最后一個身份值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.