How to copy data in identity column?

北城以北 提交于 2020-02-03 08:51:13

问题


I have a table with an identity column in a server and have a other table with same structure in another server.. Now I want to copy all data from one table to other table but I can't help it...

I have already created a linked server..

I use this:

insert into [server].[database].[dbo].[table1]
    select *
    from table2

I also use this query without identity column in the place of *

insert into [server].[database].[dbo].[table1]
   select column1, column2
   from table2

What should I do ?


回答1:


If you want to insert into a second table that also has an identity column, then you need to explicitly define the list of columns you're inserting into and omit the identity column:

insert into [server].[database].[dbo].[table1] (col1, col2)
   select column1, column2
   from table2

This way, SQL Server can insert the identity values in the target table as it should

Update:

two scenarios:

(1) you want to insert the existing values from the identity column from the old table into the new one - in that case, you need to use SET IDENTITY_INSERT ON/OFF in your query:

SET IDENTITY_INSERT [192.168.1.6].[audit].[dbo].[tmpDTTransfer] ON 

INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer] (id, code, transfer1)
   SELECT  
       id, code, transfer1 
   FROM 
       tmpDTTransfer 

SET IDENTITY_INSERT [192.168.1.6].[audit].[dbo].[tmpDTTransfer] OFF

(2) if you don't want to insert the existing identity values, but just the other columns and let SQL Server assign new identity values in the target table, then you don't need to use SET IDENTITY_INSERT ON/OFF in your query:

INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer] (code, transfer1)
   SELECT  
       code, transfer1 
   FROM 
       tmpDTTransfer 

But in any you, you should always explicitly define the list of columns to insert into, in your target table.

DO NOT USE:

INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer] 
   .......

But instead use

INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer] (Code, Transfer1)
   .......

or

INSERT INTO [192.168.1.6].[audit].[dbo].[tmpDTTransfer] (Id, Code, Transfer1)
   .......

or whatever you need. Be explicit about what you want to insert into!




回答2:


Set IDENTITY_INSERT for table:

  SET IDENTITY_INSERT [server].[database].[dbo].[table1] ON
  insert into [server].[database].[dbo].[table1]
  select column1,column2
  from table2
  SET IDENTITY_INSERT [server].[database].[dbo].[table1] OFF



回答3:


If you don't need to necessarily use SQL script, than you can do it using SQL Server Import and Export Wizard. You can read the tutorial here on MSDN.



来源:https://stackoverflow.com/questions/32002876/how-to-copy-data-in-identity-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!