1

我的问题可能听起来很愚蠢,但我被困住了。这是我在 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

希望大家给点建议。。。

4

4 回答 4

2

使用变量

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
于 2012-11-26T11:03:16.963 回答
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

注意。使用Ident_Current@@Identity更容易产生不良副作用。

http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/

于 2012-11-26T11:03:07.847 回答
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,..)
于 2012-11-26T11:06:15.697 回答
0

使用您的伪代码来塑造一个存储过程:getEmployeeId_byEmail.

存储过程的第二个块将获得新的 EmployeeId @@Identity

/* untested */
insert into employee values(/*what ever*/)
insert into task(/*what ever*/, @@Identity)

看看这里

于 2012-11-26T11:07:44.170 回答