Reputation: 5427
I have this code, i'm trying to set the identity seed by a varable
DECLARE @iKeyX INT
SELECT @iKeyX = MAX(KeyX) FROM Temporales..tmp_Orders
IF (@iKeyX = NULL)
SET @iKeyX = 1
ELSE
SET @iKeyX = @iKeyX + 1
IF OBJECT_ID('tempdb..#tmp_Orders','U') IS NOT NULL
DROP TABLE #tmp_Orders
SELECT IDENTITY(INT, @iKeyX, 1) AS KeyX,
0 AS Valido,
OrderNumber,
OrderType,
Code,
Size,
INTO #tmp_Orders
FROM TableWithData
Why SQL keeps telling me "Incorrect syntax near '@ iKeyX'"?
Upvotes: 2
Views: 2936
Reputation: 13419
This appears to be an old bug in SQL Server that has never been fixed. To work around the problem (as suggested in the link), build the command into a string and then execute the string.
Workaround from the link:
DECLARE @SQL varchar(8000)
DECLARE @myident int
SET @myident = 100
SET @sql = 'SELECT IDENTITY(INT, ' + CAST(@myident as varchar) + ', 1) AS ident INTO #T2'
EXEC(@sql)
SELECT @@identity
Upvotes: 1
Reputation: 700
Because I don't like adding statements into a string.. 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
Upvotes: 1