【问题标题】:How can I best create an employee AND certifications record in my tables?我怎样才能最好地在我的表中创建员工和认证记录?
【发布时间】:2021-02-09 19:25:02
【问题描述】:

我正在设计可能同时供多人使用的软件。 我的程序将能够“创建员工”,这需要填写一个表单,然后在 SQL 查询中使用该表单将记录插入到EmployeeEmployeeCertifications

现在,Employee.id 是一个主键和标识列。我有两个存储过程,Employee_CreateEmployee(将记录插入Employee)和Employee_CreateCertifications(将记录插入EmployeeCertifications,并带有provided emp_id)。

我正在将这些存储过程集成到我的软件中的员工创建过程中,但我面临一个潜在问题,即在给定时刻有多个用户尝试创建员工。我最初是想让我的程序执行Employee_CreateEmployee,然后运行查询以获得最高的id(最近创建的员工),并将结果用于过程Employee_CreateCertifications

有没有更好的方法来解决这个问题?我曾考虑过可能对所有这些查询和执行使用事务,但不知道这是否也会为错误留下空间。

【问题讨论】:

  • @DaleK 如果您不介意展示我如何返回 ID,我很乐意接受这个答案!

标签: sql sql-server tsql stored-procedures


【解决方案1】:

使用scope_identity 获取插入的最新ID,并在您的第一个存储过程中使用output parameter 以返回新ID 供第二个使用:

create procedure dbo.Test1
(
    @Input1 nvarchar(128)
    -- ...
    , @NewId int out
)
as
begin
    set nocount, xact_abort on;

    insert into dbo.MyTable (Column1 /* 2, 3... */)
      select @Input1; -- @Input2, @Input3 ...

    set @NewId = scope_identity();

    return 0;
end;

然后调用为:

exec dbo.Test1 @Input1, @NewId out;

exec dbo.Test2 @NewId, @OtherInput1;

【讨论】:

  • @sirius_pain 也可以随意使用事务..
猜你喜欢
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
相关资源
最近更新 更多