Skip to content

Cross database queries – or, how to rescue a bad database

Even InaPlex gets it wrong occassionally.

It was late, we were tired, instructions from the client were not clarified properly… and the database was not backed up before a SQL update was issued that created some real problems. The SQL update modified the primary userid of most of the account records in the CRM system.

Of course, the problems were not discovered until the next morning – second last day of the financial year for the client, and the sales people could not see all their accounts in the CRM system because they no longer had appropriate permissions.

The project manager at the client was very polite, but was clearly under substantial pressure to get it fixed.

But the database was live, had been modified, and the most recent backup was a few days old. Rolling back to the backup was out of the question, continuing with the current system was impossible for the sales people.

All in all, not a good situation.

One of the very useful, and relatively unknown, features of SQL in Microsoft SQL Server is that it is possible to execute cross-database queries. This means it is possible to have queries that uses tables from more than one database. Very importantly from our perspective, it means that data in database A can be updated from data in database B.

This gave us a path out of the problem. The old backup was restored to a temporary database, and then a cross database query was used to retrieve the correct field value from the restored database, and update it in the live database. Here’s an example of the type of query used:

set =, =
from inner join
      on =
-- where = 59598

This query shows updating the main crm database from the “temp” database, which is the restored backup. The value: “” is the fully qualified name of a field:


Using the fully qualified name, we are able to join the live table and its copy in the backup, and selectively update the damaged fields from the backup.

The commented out “where” clause shows how the query was tested before updating the whole database – a single record ID selected, the query run on that record, and then the results examined.

The cross database query restored the database to a useable stte and, the sales team was able to complete their day. Later, InaPlex very carefully completed the migration – after taking a backup…

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: