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)
 Auto increment ident column with criteria

Author  Topic 

cornall
Posting Yak Master

148 Posts

Posted - 2012-02-20 : 07:19:03
Hi,

Is it possible to have an auto incramneting identity column with criteria.

e.g.

I have table 1

id
desc

table 2

id
fkTable1Id
desc
id2

I want id2 to be based on groups of fkTable1Id

Hope this makes some sense!

So if I do the following inserts and deletes into table 2

Insert

NULL,1,'some text',NULL
NULL,1,'some text',NULL
NULL,1,'some text',NULL
NULL,1,'some text',NULL

DELETE from table 2 where Id

1
4

Insert into table 2

Insert

NULL,2,'some text',NULL
NULL,1,'some text',NULL


I end up with

2,1,'some text',2
3,1,'some text',3
5,2,'some text',1
6,1,'some text',5


visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-02-20 : 11:39:57
sorry didnt get that. can you explain how you hgot 1 and 5 for last two rows?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

cornall
Posting Yak Master

148 Posts

Posted - 2012-02-21 : 04:28:37
I want my second identity column to be based on fkTable1Id

there were 4 inserts for forign key 1 then two deletes and a final insert resulting in an id of 5

there was one insert for forign key 2 resulting in an id of 1

Sorry it is hard to explain!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-02-21 : 14:23:26
looks like what you need is to use ROW_NUMBER() OVER (PARTITION BY fkTable1Id ORDER BY id) and update id2 with it

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -