3

I have a table in SQL Server with data that has an auto-increment column. The data in the auto increment column is not sequential. It is like 1, 2, 3, 5, 6, 7, 9 (missing 4 and 8).

I want to copy the exact data in this table to another fresh and empty identical table. The destination table also has an auto increment column.

Problem: when I copy the data using the query below, the AttachmentID has new and different values

INSERT INTO FPSDB_new.dbo.Form_Attachment
    SELECT
        CategoryID
    FROM
        FPSDB.dbo.Form_Attachment

the Form_Attachment table in destination and source is same as below

CREATE TABLE [dbo].[Form_Attachment] 
(
    [AttachmentID] [int] IDENTITY(1,1) NOT NULL,
    [CategoryID]   [int] NULL
)

Is there a SQL query solution to make the two tables with identical data?

3 Answers 3

8

You can insert into an IDENTITY column by using SET IDENTITY_INSERT ON in your transaction (don't forget to turn it off afterwards):

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

SET IDENTITY_INSERT FPSDB_new.dbo.Form_Attachment ON

INSERT INTO FPSDB_new.dbo.Form_Attachment ( AttachmentID, CategoryID )
SELECT
    AttachmentID,
    CategoryID
FROM
    FPSDB.dbo.Form_Attachment

SET IDENTITY_INSERT FPSDB_new.dbo.Form_Attachment OFF
Sign up to request clarification or add additional context in comments.

2 Comments

your answer is correct but if I have data inside the Destination table and I want to replace the rows with that of Source table. Then how can I update the rows of the destination table
@shomaail you will need to DELETE matching rows first. Alternatively look at the MERGE operation.
1

You can use this command: SET IDENTITY_INSERT to ON

Comments

1

You can also do this:

  1. Drop the copy table

  2. Create as select, which will copy the exact structure and data to the new table.

    Select * 
    into new_table  
    from old_table 
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.