Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 创建表标识中的变量_Sql Server - Fatal编程技术网

Sql server 创建表标识中的变量

Sql server 创建表标识中的变量,sql-server,Sql Server,我在SP中有一个临时表 CREATE TABLE #bclist ( bcastid INT ,userid INT ,etype INT ,articles0 BIGINT ,seq INT identity(1, 1) ) 我还有一个变量@nextseq 我想要的是下面这样的东西 CREATE TABLE #bclist (

我在SP中有一个临时表

CREATE TABLE #bclist (
            bcastid INT
            ,userid INT
            ,etype INT
            ,articles0 BIGINT
            ,seq INT identity(1, 1)
            )
我还有一个变量@nextseq 我想要的是下面这样的东西

CREATE TABLE #bclist (
            bcastid INT
            ,userid INT
            ,etype INT
            ,articles0 BIGINT
            ,seq INT identity(@nextseq, 1)
            )
但是SQl server不允许这样做。有解决方案吗?

您可以使用

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

不要忘记if条件,否则在seq coulmn中,将从2而不是1获得值

全局临时表怎么样

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

也许你应该把你想解决的“实际”问题贴出来;闻起来像是一个row_number()解决方案。。。