In additiona to what Lowell has shown, there is a parameter available that defines the database to be used for the query: @query_database (I think - look it up to be sure).
Using that parameter will make sure the query is executed in the context of that database.
Jeffrey Williams
“We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”
― Charles R. Swindoll
How to post questions to get better answers faster
Managing Transaction Logs