SQL Server Reset Identity Increment for all tables

前端 未结 9 1522
面向向阳花
面向向阳花 2021-01-30 05:38

Basically I need to reset Identity Increment for all tables to its original. Here I tried some code, but it fails.

http://pastebin.com/KSyvtK5b

Actual code from

9条回答
  •  鱼传尺愫
    2021-01-30 06:15

    Use the below code,

    CREATE TABLE #tmptable
    (
        [seednvalue] int not null,
        [tablename] [nvarchar] (100) NULL
    ) 
    
    
    declare @seedvalue AS INT
    DECLARE @tablename AS VARCHAR(100)
    
    Declare #tablesIdentityCursor CURSOR
        for 
        SELECT 
        IDENT_CURRENT(TABLE_NAME)+1 AS Current_Identity,
        TABLE_NAME
        FROM INFORMATION_SCHEMA.TABLES
        WHERE OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 1
        AND TABLE_TYPE = 'BASE TABLE'  --AND TABLE_NAME='test11'
    
    delete from #tmptable
    Open #tablesIdentityCursor
    FETCH NEXT FROM #tablesIdentityCursor into @seedvalue, @tablename
    WHILE @@FETCH_STATUS = 0 BEGIN
    
        Insert into #tmptable Select @seedvalue , @tablename   
        DBCC CHECKIDENT (@tablename, reseed, @seedvalue) 
        FETCH NEXT FROM #tablesIdentityCursor into @seedvalue, @tablename
    END
    CLOSE #tablesIdentityCursor
    DEALLOCATE #tablesIdentityCursor
    SELECT * FROM #tmptable
    DROP TABLE #tmptable
    

提交回复
热议问题