2011-11-12 70 views
2

我有一個SP臨時表。變量創建表識別

CREATE TABLE #bclist (
      bcastid INT 
      ,userid INT 
      ,etype INT 
      ,articles0 BIGINT 
      ,seq INT identity(1, 1) 
      ) 

我也有一個變量@nextseq 我要的是somthingh像下面

CREATE TABLE #bclist (
      bcastid INT 
      ,userid INT 
      ,etype INT 
      ,articles0 BIGINT 
      ,seq INT identity(@nextseq, 1) 
      ) 

但SQL Server不允許這樣。任何解決方案?

+0

也許你應該張貼您正在試圖解決的 '實際' 的問題;聞起來像一個row_number()解決方案... –

回答

2

您可以使用

DBCC CHECKIDENT (#bclist, RESEED, @nextseq) 

但是,如果你不能對SP進行運行的dbowner它不會工作。 你可以做的另一件事是重新安排表格。

if @nextseq > 1 
     begin 
       TRUNCATE table #bclist 
      SET IDENTITY_INSERT #bclist ON 
      INSERT INTO #bclist (seq) 
      VALUES (@nextseq-1) 
      SET IDENTITY_INSERT #bclist OFF 
      DELETE FROM #bclist 
     End 

否則不要忘了,如果條件你SEQ coulmn您將從2,而不是1

0

獲得價值如何全局臨時表?

DECLARE @foo varchar(5); 
SET @foo = '4'; 

DECLARE @query nvarchar(max); 

-- a global temp table will exist for the lifetime of 
-- the connection 
SET @query = replace(N' 
CREATE TABLE ##bclist (
      bcastid INT 
      ,userid INT 
      ,etype INT 
      ,articles0 BIGINT 
      ,seq INT identity(@seed, 1) 
      )', '@seed', @foo) 

EXECUTE(@query) 

INSERT INTO 
    ##bclist 
SELECT 0,1,2,3 
select * from ##bclist 

drop table ##bclist 

結果

bcastid userid etype articles0 seq 
0   1  2  3   4