Reputation: 1740
I have a table user
with columns
Id | Name | Email
I have another table employee
with columns
Id | UserId | Designation
Is there a way to write a stored procedure where I insert a row into User
and get the Id
, and then use that Id
(as UserId
) to insert a row into the Employee
table?
Upvotes: 1
Views: 2837
Reputation: 754398
Of course - no problem - try code something like this:
CREATE PROCEDURE dbo.InsertUserAndEmployee
(@Name VARCHAR(100),
@Email VARCHAR(255),
@Designation VARCHAR(100)
)
AS
BEGIN
-- Insert into "User"
INSERT INTO dbo.User (Name, Email)
VALUES (@Name, @Email);
-- get the newly inserted ID
DECLARE @UserId INT;
SELECT @UserId = SCOPE_IDENTITY();
-- Insert into "Employee"
INSERT INTO dbo.Employee (UserId, Designation)
VALUES (@UserId, @Designation);
END
Upvotes: 4