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"
what you need is SCOPE_IDENTITY() function, it returns last ID within a scope
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)
ummm... the answer is really simple, just write a procedure with error handling etc.
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
Assuming your unknown fields are coming in as parameters:
Inside your stored proc...
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 and @@IDENTITY return the last identity values that are generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.
您可以使用原始插入内容,但您可以使用第一个表中插入的身份 ID SCOPE_IDENTITY()
,它返回为当前会话和当前范围中的任何表生成的最后一个身份值。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.