与变量种子的身份

时间:2012-06-28 15:14:42

标签: sql tsql variables dynamic identity

我有这个代码,我正在尝试通过可变量

设置身份种子
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

为什么SQL一直告诉我“'iKeyX'附近的语法不正确”?

2 个答案:

答案 0 :(得分:1)

这似乎是SQL Server中的old bug,从未修复过。要解决此问题(如链接中所示),请将命令构建为字符串,然后执行字符串。

链接中的解决方法:

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

答案 1 :(得分:1)

因为我不喜欢在语句中添加语句.. 我最终做了以下事情:

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'

谢谢