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)
 Like IDENTITY

Author  Topic 

daidaluus
Yak Posting Veteran

73 Posts

Posted - 2007-12-12 : 05:37:52
I have a table with an id column which is not defined as IDENTITY. Every time that I want to insert into this table I should calculate MAX of id and increment this value for each inserted row, much like a real IDENTITY columns. For some reasons I cant set it as IDENTITY. I want to do something like this:

@id = Get Max Id

INSERT INTO Tbl (id, col1, col2, ...)
SELECT IncrIdForEachInsertedRow(@Seed=@id+1), col1, col2, ...
FROM AnyTbl
WHERE Condition

I had done it with temporary table. Is there any way to do it in a single insert statement?

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-12-12 : 06:02:48
INSERT TargetTable (PkCol, Col1, Col2)
SELECT COALESCE((SELECT MAX(PkCol) FROM TargetTable), 0) + 1, Col1, Col2
FROM SourceTable



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

daidaluus
Yak Posting Veteran

73 Posts

Posted - 2007-12-12 : 06:10:21
It works if just one row will be inserted. for more-than-one-rows inserts it repeats that MAX+1 for all newly inserted row. I look for a way that any new inserted row have its own id.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2007-12-12 : 12:22:45
Not sure it works but you can try writing a INSTEAD OF trigger on table for insert and set value of id column as MAX(pk)+1 inside this. But this will surely have a performance hit.
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2007-12-12 : 13:37:16
Can you put an IDENTITY on the temp table and then use that ID to add to the MAX ID from the target table?
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2007-12-12 : 14:02:59
Read this

http://weblogs.sqlteam.com/brettk/archive/2004/06/29/1687.aspx



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page
   

- Advertisement -