从sql中的select中获取id

时间:2012-11-26 10:59:39

标签: sql sql-server sql-server-2005

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

答案 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更容易产生不良副作用。

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

答案 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