首页 > 解决方案 > 如何在 SQL Server 中使用 SEQUENCE PK 列创建临时表

问题描述

我可以使用序列创建表,但是当我尝试将序列用于临时表时,出现错误:

无效的对象名称“[序列]”

我无法使用临时表的序列添加到主键吗?如果我只是将其更改@tisttist标准表,则一切正常...问题是我需要使用临时表...由于权限而不是实际表。

    drop table if exists #tist
    drop table if exists #t_stg 

    drop sequence if exists i_seq
    go

    create sequence i_seq start with 1 increment by 1

    /* Error is this Line */
    create table #tist(id int primary key default (next value for dbo.i_seq), a int, b int)

    create table #t_stg(id int, a int, b int)

    insert into #t_stg(a,b) values (1,2),(3,3),(4,5)

    update #t_stg set id = next value for i_seq

    --select * from #t_stg

    insert into #tist(id,a,b) 
    select * from #t_stg 

    SELECT * FROM #tist

标签: sql-serversequencetemp-tables

解决方案


在我简单地用我的序列更新 STAGING 表而不是尝试使用 SEQUENCE 创建我的 TEMP TABLE 之后,似乎得到了我想要的东西。

DROP TABLE IF exists #t
DROP TABLE IF exists #t_stg 

DROP SEQUENCE IF exists dbo.t_seq

GO

DECLARE @sql NVARCHAR(max);
DECLARE @Count INT = 981518;

CREATE SEQUENCE dbo.t_seq START WITH 1 increment BY 1

SET @sql = N'ALTER SEQUENCE dbo.t_seq RESTART WITH ' + CAST(@Count AS NVARCHAR(20)) + ';';
EXEC SP_EXECUTESQL @sql;
GO

CREATE TABLE #t(id INT, a INT, b INT)

CREATE TABLE #t_stg(id INT, a INT, b INT)

INSERT INTO #t_stg(a,b) VALUES (1,2),(3,3),(4,5)

--SELECT * FROM #t_stg

UPDATE #t_stg SET id = NEXT VALUE FOR t_seq

SELECT * FROM #t_stg

--INSERT INTO #t(id,a,b) 
--SELECT * FROM #t_stg

--SELECT * FROM #t

GO

推荐阅读