SQL Server Enable identity insert is not working when importing data

vecaoik1  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(145)

I am trying to import many tables from access db to MS SQL server using the import wizard. Some rows in source tables has been deleted so the sequence of IDs are like this: 2,3,5,8,9,12,...

but when I import the data into my destination, the IDs start from 1 and increment by 1, so they don't exactly match with source data.

I even check the "Enable Identity insert" but it does not help. The only work around I have found is to change the IDs in destination tables from Identity to integer one by one, then import, and then change them back to identity, which is very time consuming.

Is there any better way to do this?

dy1byipe

dy1byipe1#

If you want to insert an id in the identity column, you need to use:

SET IDENTITY_INSERT table_name ON

https://msdn.microsoft.com/es-us/library/ms188059.aspx

Remember to set it OFF at the end of the script.

Possible Work-arounds

Well, since this answer doesn't seem to fullfill all requirements, I'm going to expand on it a bit more. The import/export wizard from the SQL Server Management Studio is basically an implementation of SQL Server Integration Services. If you need to build a package that has a few extra steps, you might want to consider SSIS as an option (it comes with SQL Server licenses so you don't have to pay any extras and it is available to use in Visual Studio). It will allow you to do the same task but also run SQL scripts on the database. It's a low code tool so it is very straight forward for this kind of situations.

Another option is to use the import wizard as it is to import into a "staging" table. So, instead of overwritting the destination table, you would:

  1. Insert into a staging table (which should have the same structure as the destination table but making the IDENTITY column just an integer).
  2. You import your data into this staging table.
  3. Then you can run the following script to insert into the correct table.
SET IDENTITY_INSERT table_name ON

INSERT INTO table_name SELECT * FROM staging_table_name

SET IDENTITY_INSERT table_name OFF

Finally check that everything was inserted correctly and drop the staging table.

These are at least 2 possible ways to get the job done.

相关问题