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 2005 Forums
 Transact-SQL (2005)
 Insert Multimple Tables

Author  Topic 

jerryleguer
Starting Member

2 Posts

Posted - 2010-12-03 : 10:04:07
Hello,

I need to insert in to tow tables. The firts table creates an Identity and that identity has to be inserted into the second table.

Table 1
id (identity)
Failed
Comments

Table 2

id
type
idtable1
date
Comments

I need to insert a new record on table and then insert a new record in table 2 using the table 1 identity row for the idtable1.

Thans

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2010-12-03 : 10:13:01
declare @id int
insert tbl1 (failed, comments) select 'asdfafd', 'csc\x'
select @id = scope_identity()
insert tbl2 (type, idtable1, date, comments)
sleect 1, @id, getdate(), 'fdsgsfg'

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

bobmcclellan
Starting Member

46 Posts

Posted - 2010-12-03 : 10:14:28
declare @si int
Insert into table 1 (...)

set @si = scope_identity()
Insert into table 2 (id, ...
values ( @si, ... )
hth,
bob
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2010-12-03 : 11:57:33
Don't forget to wrap both inserts in a transaction.

Or you can use an Output Clause and do it in one unit of work:
http://blog.sqlauthority.com/2007/10/01/sql-server-2005-output-clause-example-and-explanation-with-insert-update-delete/
Go to Top of Page
   

- Advertisement -