我有两张桌子
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)
嗯...答案很简单,只需编写一个错误处理程序等。
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()
,它返回为当前会话中的任何表和当前范围生成的最后一个标识值。