Set IDENTITY_INSERT OFF for all tables

前端 未结 5 1919
轮回少年
轮回少年 2020-12-28 14:02

I have a script which creates an entire database and inserts all records to a few dozen tables. It works great, unless there is some issue during the processing, and a table

5条回答
  •  别那么骄傲
    2020-12-28 14:33

    I had a similar issue but I'd rather not use undocumented stored procedures in production. To automate this I built on to @John Dewey's answer and put it into a cursor. This iterates over 699 tables in 407 ms.

    DECLARE @sql NVARCHAR(500) -- SQL command to execute
    
    DECLARE sql_cursor CURSOR LOCAL FAST_FORWARD FOR
    SELECT 'SET identity_insert ['+s.name+'].['+o.name+'] OFF'
    FROM sys.objects o
    INNER JOIN sys.schemas s on s.schema_id=o.schema_id
    WHERE o.[type]='U'
    AND EXISTS(SELECT 1 FROM sys.columns WHERE object_id=o.object_id AND is_identity=1)
    
    OPEN sql_cursor
    FETCH NEXT FROM sql_cursor INTO @sql
    
    WHILE @@FETCH_STATUS = 0
        BEGIN
            EXECUTE sp_executesql @sql  --> Comment this out to test
            -- PRINT @sql   --> Uncomment to test or if logging is desired
            FETCH NEXT FROM sql_cursor INTO @sql
        END
    
    CLOSE sql_cursor
    DEALLOCATE sql_cursor
    

    If you are against cursors, it could also be easily transformed into a while loop.

提交回复
热议问题