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 2012 Forums
 Transact-SQL (2012)
 Output clause to get new id and source id

Author  Topic 

nickfinity
Yak Posting Veteran

55 Posts

Posted - 2014-11-23 : 22:49:04
I don't think this is possible, but I thought I'd ask just in case. Let's say I have a simple table.


CREATE TABLE [table1] (
[table1_id] INT identity(1,1) NOT NULL,
[name] VARCHAR (150) NOT NULL,
[other_column] VARCHAR (10) NOT NULL
CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED ([table1_id] ASC))

I need to copy some records and get the source id and the new id. At first I thought I might be able to do something like this:

DECLARE @tableVar table(
sourceId int NOT NULL,
targetId int NOT NULL
);

insert into table1 (name, other_column)
OUTPUT table1.table1_id,/*what can i put here?*/
INSERTED.table1_id
INTO @tableVar
select name, other_column
from table1
where other_column = 'X'

That doesn't work, of course, because I'm not selecting table1.table1_id in the select statement. And I don't think I can select it because it's an identity column and I can't pull an extra column as far as I know when doing an insert into..select. Can I use a merge statement?

Any suggestions? I sincerely appreciate any help. Apologies if I missed this question in my search.

Thanks,
Nick

nickfinity
Yak Posting Veteran

55 Posts

Posted - 2014-11-24 : 06:03:23
I think I figured it out using a merge statement. I'll post it a little later and maybe someone can tell me if it's the best way to do it.
Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-11-24 : 11:05:36
This is confusing to me. Your query inserts rows into table1 from table1, resulting in duplicate rows. Is that what you want?
Go to Top of Page
   

- Advertisement -