How to create sequence in SQL Server 2008

后端 未结 6 1434
执笔经年
执笔经年 2021-01-02 23:37

I am creating sequence in SQL Server with the following code. But it displays error as unknown object type. Please give a solution

Here\'s my code :

         


        
6条回答
  •  一向
    一向 (楼主)
    2021-01-03 00:13

    Create a Numbers table; here's a SO question on the subject. Let's call it dbo.Number.

    Have a table with an identity column. Set the seed and step to whatever is appropriate:

    create table dbo.SequenceGenerator(ID int identity(1, 1), dummy int);
    

    Then insert values from the numbers table and capture the newly-generated identity values:

    declare @HowMany int = 3;  -- This determines how large a sequence you receive
                               -- at each itteration
    declare @NewSequenceValue table (ID int);
    
    insert dbo.SequenceGenerator(dummy)
    output INSERTED.ID 
        into @NewSequenceValue
    select Number from dbo.Numbers
    where Number <= @HowMany;
    
    select * from @NewSequenceValue;
    

    Be sure to DELETE .. dbo.SequenceGenerator from time to time, else it will get big for no additional value. Do not TRUNCATE it - that will reset the IDENTITY column to its initally-declared seed value.

提交回复
热议问题