SQL Server Generate Scripts with Identity Insert

Adam Levitt picture Adam Levitt · Oct 2, 2012 · Viewed 8.6k times · Source

When generating database scripts, I'm scripting data to be migrated to a different environment. Is there a setting in the script generation that I can enable to set IDENTITY_INSERT on/off automatically so I don't have to go through each table manually in the generated script and set it? I'm using SSMS and I'd like to do this via SSMS.

Here's what I am getting:

INSERT my_table (my_table_id, my_table_name) VALUES (1, 'val1');
INSERT my_table (my_table_id, my_table_name) VALUES (2, 'val2');

Here's what I want:

SET IDENTITY_INSERT my_table ON
INSERT my_table (my_table_id, my_table_name) VALUES (1, 'val1');
INSERT my_table (my_table_id, my_table_name) VALUES (2, 'val2');
SET IDENTITY_INSERT my_table OFF

Answer

SqlZim picture SqlZim · Dec 25, 2016

I know this is an old question, but the accepted answer and the comments to the accepted answer aren't quite correct regarding SSMS.

When using the generate scripts task in Sql Server Management Studio (SSMS) to generate scripts with data, set identity_insert statements will be included for tables that have an identity column.

In the object explorer: Tasks -> Generate Scripts -> [All Tables or selected tables] -> Advanced -> [Schema with Data or Data]

  • If the table to script data from does not have a column with the identity property , it will not generate the set identity_insert statements.

  • If the table to script data from does have a column with the identity property , it will generate the set identity_insert statements.

Tested & Confirmed using SSMS 2008 & SSMS 2012

In the OP's situation, I'm guessing the origin table did not have the identity property set for my_table_id in the source table, but the identity property was set for my_table_id in the destination table.

To get the desired output, change the table to script data from to have my_table_id to have the identity property.

This article explains in depth the steps to do this (without using the designer in SSMS): Add or drop identity property for an existing SQL Server column - Greg Robidoux

  • Create a new column with the identity property

  • Transfer the data from the existing id column to the new column

  • Drop the existing id column.

  • Rename the new column to the original column name