SQL Server AutoIncrement varying by value of another field

非 Y 不嫁゛ 提交于 2019-12-23 02:44:17

问题


Using SQL Server 2008 R2 I'd like to have a table (already having a primary key on 2 columns) with a third column which is an autoincrement based on one of the two columns part of the primary key.

In other terms, I would like when adding a new record to the table, have an autoincrement file AIfield automatically incremented as follows:

  PK1 PK2  AIfield 
  ------------------
  1   A     1
  1   B     2
  1   C     3
  2   A     1
  2   B1    2
  2   B2    3
  2   C1    4

where PK1 and PK2 are the two fields of the primary key.

I do not want to use the obvious MAX(Afield)+1 approach, since it's very likely that I have to do concurrent inserts for the same PK1 - which would sooner or later create duplicates in AIfield for the same PK1.

Any suggestions?


回答1:


select pk1,pk2,ROW_NUMBER() over (partition by pk1,pk2 order by (select 0)) as AIfield
from yourtable



回答2:


Well, an approach could be creating a unique Index on PK1 and AIfield

CREATE UNIQUE NONCLUSTERED INDEX [test] ON [Table] 
(
[AIfield] ASC,
[PK1] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF,  
IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, 
 ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

and handling violations of uniqueness

DECLARE @inserted BIT=0
DECLARE @AIfield BIGINT
SELECT @AIfield=MAX(AIfield)+1 FROM Table WHERE PK1=@PK1
WHILE @inserted=0
BEGIN
 BEGIN TRY
  INSERT INTO Table(AIfield,PK1,PK2)
  SELECT  @AIfield,@PK1,@PK2
  SET @inserted=1
 END TRY
 BEGIN CATCH
    IF ERROR_NUMBER()=2601
     BEGIN
     SET @AIfield=@AIfield+1
     END
    ELSE SET @inserted=1
 END CATCH
END

I wonder if there is an approach more SQL native, though




回答3:


Use below query :

Select PK1, PK2, ROW_NUMBER() over (partition by PK1 order by PK1, PK2) as AIfield
From yourtable


来源:https://stackoverflow.com/questions/12152790/sql-server-autoincrement-varying-by-value-of-another-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!