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
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.
Dynamic SQL:
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)
Then copy & paste the resulting SQL into another query window and run
EXEC sp_MSforeachtable @command1="SET IDENTITY_INSERT ? OFF"
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)'
Building on Lynn's answer, in case you're too lazy to perform this in more than one step - this should run on all tables where there is an identity column.
Caveat is only tested in 2012 and sp_MSforeachtable is of course entirely unsupported...
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