我怎样才能最好地在我的表中创建员工和认证记录?
How can I best create an employee AND certifications record in my tables?
我正在设计可能同时供多人使用的软件。
我的程序将能够“创建员工”,这需要填写一个表单,然后在 SQL 查询中使用该表单将记录插入 Employee
和 EmployeeCertifications
.
现在,Employee.id
是一个主键和标识列。我有两个存储过程,Employee_CreateEmployee
(将记录插入 Employee
)和 Employee_CreateCertifications
(将记录插入 EmployeeCertifications
,并提供 emp_id
).
我正在将这些存储过程集成到我的软件中的员工创建过程中,但我面临着一个潜在的问题,即在给定时刻有多个用户试图创建一名员工。我最初想让我的程序执行 Employee_CreateEmployee
,然后 运行 查询以获得最高 id
(最近创建的员工),并将结果用于过程 Employee_CreateCertifications
.
有没有更好的方法来解决这个问题?我考虑过可能对所有这些查询和执行使用一个事务,但不知道这是否也会为错误留下空间。
在您的第一个存储过程中使用 scope_identity to obtain the latest ID inserted and use an output parameter 来 return 新 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;
我正在设计可能同时供多人使用的软件。
我的程序将能够“创建员工”,这需要填写一个表单,然后在 SQL 查询中使用该表单将记录插入 Employee
和 EmployeeCertifications
.
现在,Employee.id
是一个主键和标识列。我有两个存储过程,Employee_CreateEmployee
(将记录插入 Employee
)和 Employee_CreateCertifications
(将记录插入 EmployeeCertifications
,并提供 emp_id
).
我正在将这些存储过程集成到我的软件中的员工创建过程中,但我面临着一个潜在的问题,即在给定时刻有多个用户试图创建一名员工。我最初想让我的程序执行 Employee_CreateEmployee
,然后 运行 查询以获得最高 id
(最近创建的员工),并将结果用于过程 Employee_CreateCertifications
.
有没有更好的方法来解决这个问题?我考虑过可能对所有这些查询和执行使用一个事务,但不知道这是否也会为错误留下空间。
在您的第一个存储过程中使用 scope_identity to obtain the latest ID inserted and use an output parameter 来 return 新 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;