Create sequence inside stored procedure

Ben 1 Reputation point
2021-08-31T10:01:54.347+00:00

CREATE OR ALTER PROCEDURE spTest
@DeezNutz varchar(15)
AS
BEGIN

DECLARE
@sequence varchar(25) = 'seq_transaction' + @DeezNutz

PRINT @sequence
-- prints the concatenated string ----> seq_transactionMary

CREATE SEQUENCE @sequence
START WITH 1
INCREMENT BY 1
-- Msg 102, Level 15, State 1, Procedure spTest, Line 13 [Batch Start Line 0]
-- Incorrect syntax near '@sequence'.

END

go
EXEC SPtEST 'Mary'

Please help, thank you

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,559 questions
{count} votes

5 answers

Sort by: Most helpful
  1. Olaf Helper 41,006 Reputation points
    2021-08-31T10:23:49.173+00:00

    You can not use a variable for an object name, that's not allowed.

    The only way round is dynamic SQL: https://www.sommarskog.se/dynamic_sql.html

    Why do you want to create sequences by a stored procedure?

    0 comments No comments

  2. Viorel 112.7K Reputation points
    2021-08-31T10:24:41.35+00:00

    It seems that you must use a dynamic statement, for example:

    declare @sql as varchar(max) = concat(
    'CREATE SEQUENCE ', quotename(@sequence), '
    START WITH 1
    INCREMENT BY 1' )
    
    exec (@sql)
    

  3. EchoLiu-MSFT 14,571 Reputation points
    2021-09-01T08:15:02.75+00:00

    Hi @Ben ,

    Welcome to the microsoft TSQL Q&A forum!

    Please also refer to the following questions:
    sql server: Procedure to create sequence

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  4. Tom Phillips 17,716 Reputation points
    2021-09-02T19:33:03.1+00:00

    You should probably look at ROW_NUMBER() instead of trying to use a sequence.

    0 comments No comments

  5. Ben 1 Reputation point
    2021-10-01T21:07:43.403+00:00

    Hello OlafHelper:

    My apologies for my late reply. Priority change....
    A transaction sequence is one of many steps in opening a
    new client account.
    The code I posted is a small part of of the entire transaction
    contents.
    Thank you for your help