1

My question might sound really stupid, but I am stuck. Here is the pseudo code of what I am trying to do in 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

Hopes for you suggestions.. .

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Saghir A. Khatri
  • 3,429
  • 6
  • 45
  • 76

4 Answers4

2

use variable

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
Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
1

You can use Scope_Identity() to get the last inserted key value.

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. Using Ident_Current or @@Identity is more prone to undesirable side effects.

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

podiluska
  • 50,950
  • 7
  • 98
  • 104
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,..)
bummi
  • 27,123
  • 14
  • 62
  • 101
0

Use your pseudo code to shape a stored procedure: getEmployeeId_byEmail.

The second block of the stored procedure will obtain the new EmployeeId with @@Identity:

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

Have a look here.

Community
  • 1
  • 1
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
  • avoid using the 'sp_' prefix for user-created stored procedures, it's a reserved prefix see here: http://msdn.microsoft.com/en-us/library/dd172115(v=vs.100).aspx – fnurglewitz Nov 26 '12 at 11:12