0

I have two tables

Employee---->Id(identity),FN,LN,Address

EmpContact--->Id(identity),Empid(Above table identity value),ContactType,ContactNumber

How to write two tables insert statements in single stored procedure. The second table "EmpContact" needs the resulted Identity ID from insertion in the first table "Employee"

4

5 回答 5

0

您需要的是 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)
于 2013-01-23T11:49:30.517 回答
0

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
于 2013-01-23T11:50:23.777 回答
0

假设您的未知字段作为参数传入:

在您的存储过程中...

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)
于 2013-01-23T11:51:09.240 回答
0
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 不限于特定范围。

SCOPE_IDENTITY (Transact-SQL) - MSDN

于 2013-01-23T11:51:31.580 回答
0

您可以使用原始插入的东西,但是您可以使用第一个表中插入的标识 ID SCOPE_IDENTITY(),它返回为当前会话和当前范围中的任何表生成的最后一个标识值。

于 2016-03-16T22:39:48.013 回答