Tuesday, November 4, 2008

Inter-database Communication is Easy in T-SQL

Problem

You need to obtain data from one data source to process and store in another. You don't want your server-side-script to use two connection objects and be the slow middle-man between them, as in the diagram on the left.

Slow with two SQL Server connections and scripting vs. Optimal with only one connection.


Solution

If both data sources are databases on the same MS SQL Server, it's a piece of cake to do optimally with just one connection object and pure T-SQL.

Just do the following:
  1. Set up Security - Add the user of the destination database as a user of the source database with at least db_datareader access.

  2. Prefix foreign tables with Schema - In your SQL that writes to the destination-database, prefix all tables housed in the source(foreign)-database with their "fully qualified" position in the schema to indicate which database they reside in, as illustrated in the example below.

    Example
    Table tblSource is from of the ForeignDB database, but tblDestination is from the active database.
    insert into tblDestination (colA, colB)
    select col1, col2
    from [ForeignDB].dbo.tblSource

1 comment:

  1. I think you'd find it boring since there's no Flash work, but you could come be a server database tech guy at my work!

    ReplyDelete

Was this post helpful? Do you have questions about it? Do you want to share your own programming blog? I'd love to read your feedback.

Note: Only a member of this blog may post a comment.