david sam
david sam

Reputation: 531

How to copy data in identity column?

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 ?

Upvotes: 7

Views: 28318

Answers (3)

marc_s
marc_s

Reputation: 754598

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!

Upvotes: 17

Andrew Sklyar
Andrew Sklyar

Reputation: 293

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.

Upvotes: 2

Backs
Backs

Reputation: 24913

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

Upvotes: 3

Related Questions