SQL Server Central is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
Search:  
 
 

Generate INSERT for table with IDENTITY column

By Jesse McLain, 2008/03/07

Total article views: 777 | Views in the last 30 days: 50

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

 

By Jesse McLain, 2008/03/07

Total article views: 777 | Views in the last 30 days: 50
Your response
 
 
Related tags

Script Generator    
T-SQL    
 
Already registered?  

Free registration required

To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.

Register

E-mail address:
Password:
Password (confirm):

  

Subscriptions

We ask you to register on the site and subscribe to our newsletters. Subscribing to our newsletters gets you:

  • ALL of our content (thousands of articles, scripts, and forum postings)
  • A daily newsletter (example)
  • A weekly news round up (example)
  • The opportunity to ask and answer questions in our forums
  • A daily Question of the Day to test and help you increase your knowledge of SQL Server.

We ask that you give the newsletter a try for a week. Over 200,000 SQL Server Professionals a day find it entertaining and useful. If not, you are welcome to unsubscribe at anytime.

Steve Jones
Editor, SQLServerCentral.com