Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Generate INSERT for table with IDENTITY column

By Jesse McLain,

This stored procedure script is useful for generating INSERT statements to insert data into a table that has an identity column. What I specifically had in mind when I wrote it was to backup a table for testing, run the tests, and then if I needed to revert the table back to its original state, I could truncate it and then re-insert from the backup table. When using the Management Studio's scripting tasks to create the insert statement, it wouldn't include the identity column. Also, you would have to add the "SELECT FROM" code to it. This spd basically combines all that into one call.

Example usage:

EXEC spd_Build_Insert_Into_Stmt_With_Identity 'Invoices_Backup', 'Invoices'

Results (as text in the results pane):

TRUNCATE TABLE Invoices
SET IDENTITY_INSERT Invoices ON
INSERT INTO Invoices (
Invoices_Id,
Yr_No,
Mth_No,
Billpayer_Id,
Acct_Nbr,
Call_Cnt,
Minute_Cnt,
Usage_Charge_Amt,
Reoccuring_Charge_Amt,
Non_Reoccuring_Charge_Amt,
Discount_Amt,
Tax_Amt,
Tot_Amt,
Last_Update_Dte,
Last_Update_User_Nm)
SELECT
Invoices_Id,
Yr_No,
Mth_No,
Billpayer_Id,
Acct_Nbr,
Call_Cnt,
Minute_Cnt,
Usage_Charge_Amt,
Reoccuring_Charge_Amt,
Non_Reoccuring_Charge_Amt,
Discount_Amt,
Tax_Amt,
Tot_Amt,
Last_Update_Dte,
Last_Update_User_Nm
FROM Invoices_Backup
SET IDENTITY_INSERT Invoices OFF

Total article views: 3712 | Views in the last 30 days: 12
 
Related Articles
FORUM

Inserting zero in Identity Column

Inserting zero in Identity Column

FORUM
FORUM

Zero being inserted in identity column

Zero being inserted in identity column

FORUM

Identity insertion and updation

Identity problems

Tags
script generator    
t-sql    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones