Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Question about sql transactions

Author  Topic 

fady10
Starting Member

7 Posts

Posted - 2012-09-25 : 17:09:23
I'm making a sql transaction. First, I'm inserting a record then I use the user id that I inserted using the first statement to insert it into an other table ..

How can I make this work in the same TRAN ?

Thanks in Advance

iFunny; the funniest blog ever ! - funny comics & pictures

chadmat
The Chadinator

1974 Posts

Posted - 2012-09-25 : 17:21:07
BEGIN TRAN
<do Stuff>
COMMIT

-Chad
Go to Top of Page

fady10
Starting Member

7 Posts

Posted - 2012-09-25 : 17:26:17
I know :) the problem is about <do stuff> ..
for example :
BEGIN TRAN
<statement 1 INSERT>
<statement 2 INSERT>
COMMIT

<statement 2 INSERT> is using a field that I inserted using <statement 1 INSERT> .. How can I use that field ? and Sql server will make me able to do this ?

iFunny; the funniest blog ever ! - funny comics & pictures
Go to Top of Page

chadmat
The Chadinator

1974 Posts

Posted - 2012-09-25 : 17:30:54
Is the id an Identity column? If so, use SCOPE_IDENTITY()

-Chad
Go to Top of Page

fady10
Starting Member

7 Posts

Posted - 2012-09-25 : 17:43:30
I'll use it like this ?
BEGIN TRAN
INSERT INTO [Person] VALUES (15,'Sam','2345',0.0,'2011-04-16 00:00:00.000');
INSERT INTO [Tree] VALUES (@@IDENTITY,'5','','','','','');
COMMIT TRAN
GO



iFunny; the funniest blog ever ! - funny comics & pictures
Go to Top of Page

chadmat
The Chadinator

1974 Posts

Posted - 2012-09-25 : 17:54:45
Use Scope_Identity, not @@Identity.

I would do more like:

DECLARE @id INT

BEGIN TRAN
INSERT INTO [Person] VALUES (15,'Sam','2345',0.0,'2011-04-16 00:00:00.000')
SELECT @id = SCOPE_IDENTITY()
INSERT INTO [Tree] VALUES (@id,'5','','','','','')
COMMIT TRAN

-Chad

Go to Top of Page

fady10
Starting Member

7 Posts

Posted - 2012-09-25 : 18:30:12
Thanks man :) .. I'll give it a try

iFunny; the funniest blog ever ! - funny comics & pictures
Go to Top of Page

chadmat
The Chadinator

1974 Posts

Posted - 2012-09-25 : 18:34:02
No Problem.

-Chad
Go to Top of Page

fady10
Starting Member

7 Posts

Posted - 2012-09-26 : 19:33:45
It works ! Thanks man :)

iFunny; the funniest blog ever ! - funny comics & pictures
Go to Top of Page
   

- Advertisement -