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
I believe you can do this, but it'll have to be done in dynamic SQL - declare the tableVar in the dynamic SQL and use it there too!
It would surely be easier and result in faster code if you started it at 1 and had a secondary ID field that is calculated as MAX(HHRecId) + ID.
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
You can check the current value of an IDENTITY column by using:
DBCC CHECKIDENT (#HH)
and you can also change that later on using:
DBCC CHECKIDENT (#HH, RESEED, 42)
and that also works with a variable for the new value:
DBCC CHECKIDENT (#HH, RESEED, @IdentitySeed)
It works for local and global temporary tables (i.e. CREATE TABLE #HH (...)
or CREATE TABLE ##HH (....)
- but it doesn't seem to work with table variables :-(
Sorry, it seems you can't do this with table variables.....