1

私の質問は本当にばかげているように聞こえるかもしれませんが、私は立ち往生しています。これが私がSQLServerでやろうとしていることの擬似コードです

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

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/

于 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

ストアド プロシージャの 2 番目のブロックは、新しい EmployeeId を取得し@@Identityます。

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

こちらをご覧ください。

于 2012-11-26T11:07:44.170 に答える