存储过程以插入新员工并返回新创建的记录(包括Id)

时间:2017-03-28 05:12:04

标签: sql sql-server

100

如果没有SELECT TOP 1,我怎么能这样做,因为这可能会导致ID同时出现多个查询的麻烦

3 个答案:

答案 0 :(得分:2)

我猜这可能是最简单的方法。

CREATE PROCEDURE InsertEmployee
@RFC varchar(15), 
@FirstNames varchar(150), 
@LastNames varchar(150), 
@DOB datetime, 
@IdPosition bigint, 
@ReportsTo bigint, 
@IdBranch bigint, 
@Salary money
AS

begin

Declare @Employee_pk bigint

INSERT INTO Employee
( 
    RFC, 
    FirstNames, 
    LastNames, 
    DOB, 
    IdPosition, 
    ReportsTo, 
    IdBranch, 
    Salary
)
VALUES(@RFC, @FirstNames, @LastNames, @DOB, @IdPosition, @ReportsTo, @IdBranch, @Salary)

set @Employee_pk=SCOPE_IDENTITY()

select * from EMPLOYEE where id=@Employee_pk


end

答案 1 :(得分:1)

USE OUTPUT

CREATE PROCEDURE InsertEmployee
@RFC varchar(15), 
@FirstNames varchar(150), 
@LastNames varchar(150), 
@DOB datetime, 
@IdPosition bigint, 
@ReportsTo bigint, 
@IdBranch bigint, 
@Salary money
AS

DECLARE @INSERTEDID TABLE (ID INT)

INSERT INTO Employee
( 
    RFC, 
    FirstNames, 
    LastNames, 
    DOB, 
    IdPosition, 
    ReportsTo, 
    IdBranch, 
    Salary
) 
OUTPUT inserted.ID INTO @INSERTEDID (ID)
VALUES(@RFC, @FirstNames, @LastNames, @DOB, @IdPosition, @ReportsTo, @IdBranch, @Salary)

SELECT * FROM Employee WHERE ID IN (SELECT ID FROM @INSERTED_ID)

答案 2 :(得分:0)

Use @@Identity :

CREATE PROCEDURE InsertEmployee
 @RFC varchar(15), 
 @FirstNames varchar(150), 
 @LastNames varchar(150), 
 @DOBdatetime, 
 @IdPosition bigint, 
 @ReportsTo bigint, 
 @IdBranch bigint, 
 @Salary money
 AS

 DECLARE @LastInsertedId INT = 0   

  INSERT INTO Employee
  ( 
      RFC,     FirstNames,     LastNames,     DOB,     IdPosition, 
      ReportsTo,     IdBranch,     Salary
  )
  VALUES(@RFC, @FirstNames, @LastNames, @DOB, @IdPosition, @ReportsTo,  
         @IdBranch, @Salary)

  SELECT @LastInsertedId = @@IDENTITY

  SELECT * FROM Employee WHERE Id = @LastInsertedId