我的问题可能听起来很愚蠢,但我被困住了。这是我在SQL Server中尝试做的伪代码
if exists(select id from employee where Email='saghir@abc.com')
begin
insert in tasks with selected id
end
else
begin
insert in employee value Email='blah';
insert in tasks with new id in employee
end
希望你的建议......
答案 0 :(得分:1)
您可以使用Scope_Identity()
获取最后插入的键值。
if exists(select id from employee where Email='saghir@abc.com')
begin
insert tasks(employeeid, task)
select id, 'new task' from employee where email = 'saghir@abc.com'
end
else
begin
insert employee (email) values ('blah');
select @id = Scope_identity();
insert tasks(employeeid, task) values (@id, 'new task')
end
NB。使用Ident_Current
或@@Identity
更容易产生不良副作用。
答案 1 :(得分:1)
使用变量
declare @foundId int
select @foundId = id from employee where Email='saghir@abc.com'
if @foundId is not null
begin
insert in tasks (... @foundId... )
end
else
begin
insert in employee value Email='blah';
insert in tasks with new id in employee
end
答案 2 :(得分:0)
Declare @ID int
select @ID=id from employee where Email='saghir@abc.com'
if @ID is null
begin
insert into employee (Email,...) values ('saghir@abc.com',...)
Select @ID=ident_Current('employee')
end
insert into tasks (employee_ID,...) Values (@ID,..)
答案 3 :(得分:0)
使用伪代码来整形存储过程:getEmployeeId_byEmail
。
存储过程的第二个块将获得带有@@Identity
的新EmployeeId:
/* untested */
insert into employee values(/*what ever*/)
insert into task(/*what ever*/, @@Identity)
看看here。