Set IDENTITY_INSERT OFF for all tables

前端 未结 5 1936
轮回少年
轮回少年 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:50

    Building on @KevD's answer - It was working fine for disabling but here is more for enabling as well.

    To disable all identity inserts where they need to be disabled, use -

    EXEC sp_MSforeachtable @command1="PRINT '?'; SET IDENTITY_INSERT ? OFF",
    @whereand = ' AND EXISTS (SELECT 1 FROM sys.columns WHERE object_id = o.id  
    AND is_identity = 1) and o.type = ''U'''
    

    To enable all identity inserts where they need to be enabled, use -

    EXEC sp_MSforeachtable @command1="PRINT '?'; SET IDENTITY_INSERT ? ON",
    @whereand = ' AND EXISTS (SELECT 1 FROM sys.columns WHERE object_id = o.id  
    AND is_identity = 1) and o.type = ''U'''
    

    Tested on Sql server 2014 and 2016

提交回复
热议问题