2012-06-28 47 views
1

我有這樣的代碼,我試圖通過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 

爲什麼SQL不斷告訴我「附近有語法錯誤@ iKeyX'」設置標識種子?

+0

我我在這裏做一個假設:'IDENTITY'不能把一個變量作爲一個參數。 – Oded

回答

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

因爲我不喜歡加入語句轉換成字符串.. 最後我做了以下內容:

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' 

謝謝