Programmatically set identity seed in a table variable

后端 未结 3 827
你的背包
你的背包 2021-01-18 06:30

I need to create a table variable with an identity seed that starts with the max value of a field in another table?

I\'ve tried this:

DECLARE @Identi         


        
3条回答
  •  情话喂你
    2021-01-18 07:26

    I ended up doing the following:

    DECLARE @NewId INT
    
    SELECT @NewId = MAX(ID) FROM MyIDSTable
    
    DECLARE @MyTempData TABLE (
        Id int not null primary key
        ,Field1 int not null
        ,Field2 nvarchar(25) not null
        ,Field3 datetime
    )
    
    INSERT INTO @MyTempData
    SELECT  ROW_NUMBER() OVER ( Order by [C].[Cancel_id] ASC) + @NewId -1 [RowNum]
            ,Field1
            ,Field2
            ,Field3
    
    INSERT INTO MyTable SELECT * FROM @MyTempData
    
    UPDATE MYIDSTable SET ID = (SELECT MAX(ID) FROM @MyTempData) + 1 WHERE Name = 'Something'
    

    Thank you

提交回复
热议问题