Inserting SQL

Posted on 2012-09-17
Last Modified: 2012-10-02

I have two separate databases.  DB01 and DB02

DB01 contains data that is not present in DB02 and the task here is to get data from DB01 into DB02.

I have so far written an SQL statement to get the data that I need displayed.  Can this be easily turned into the relevant insert statements?

Any other suggestions appreciated.  I’m using SQL Server  Management Studio?

Thanks in advance.
Question by:andyw27
    LVL 5

    Expert Comment


    I am sure i can help. But I will need a sample query that you have to displaying the data.

    I can then quickly give you an equivalent insert query.

    Also, help me understand if both the databases are on the same server?
    LVL 6

    Accepted Solution

    Hi  andyw27,

    I hope the below query can give u a hint on how to go about the insertion of data.
    insert DB02.TableName
    select * from DB01.TableName a
    where not exists (select 1 from DB02.TableName b where b.ColumnName = a.ColumnName )

    Open in new window

    In the above example column ColumnName ought to be a unique field that identifies the record in the table.

    Hope it helps.

    LVL 29

    Expert Comment

    by:Olaf Doschke
    As you already have a query displaying the data you want in db02, just make sure it has all fields in the table field order and you can do

    insert into db02.dbo.table
    (....your select from db01.dbo.table here...)

    The only other prerequisite is both databases are on the same server instance, so you can address the tables as db01.dbo.table and db02.dbo.table.

    Bye, Olaf.

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
    Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
    Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
    Via a live example, show how to setup several different housekeeping processes for a SQL Server.

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now