Search code examples
sql-serversequencetemp-tables

How to CREATE a Temp table in SQL Server with a SEQUENCE PK Column


I am able to create a table with a sequence, however when I attempt to use a sequence for a temp table, I get an error:

Invalid object name '[sequence]'

Am I not able to add to a primary key using a sequence to a temp table? If I simply change @tist to tist making it a standard table it all works... problem is I need to make use of a temp table... not an actual table due to permissions.

    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

Solution

  • Seems like to get what I'm after I simply update the STAGING table with my sequence rather than attempting to CREATE my TEMP TABLE using the SEQUENCE.

    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