I’m trying to write a stored procedure to copy a subset of data from one set of tables to an identical set of tables in a different database. The “source” database needs to be a parameter to the stored procedure.
I’ve struggled with this for two days now, and I thought I had a good solution:
- Validate that the schemas are the same.
- Create temporary “rmt” synonyms for the source tables using dynamic SQL.
- Copy the data using INSERT INTO A SELECT * FROM rmtA WHERE <criteria>
- Delete the synonyms.
This works pretty well for most tables, but for tables that contain an identity column, I’m forced not only to SET IDENTITY_INSERT ON & OFF, but even worse, I can’t use SELECT *; I have to specify all the columns explicitly. This will be a nightmare if I add or delete columns later.
I’ve gotta get something out the door, so I’m going with this solution for now, but I’d like to think that there’s a better solution out there somewhere.
Help?
It sounds like you’re using dynamic SQL in your stored procedure, so you’re ready to dynamically create your list of columns in the SELECT clause.
You can select from sys.columns to get the list of columns, and learn if the table has an identity column. Here’s a query that shows the information you need to create the list of columns.
In short, if
is_identityis 1 for at least one column, you’ll need to include theSET IDENTITY_INSERT. And, you would exclude any columns from the SELECT clause whereis_identity= 1.And, this approach will adapt to new columns you add to the tables.
Here’s an example