• There is no database ID for ad-hoc queries. You could try parsing the statement and figuring out which tables it uses and which DB those are in.

    But then, what database should this be associated with?

    USE master

    SELECT * FROM db1.dbo.table1

    Or this one

    Use TempDB

    SELECT *

    Into NotTemp

    FROM db1.dbo.table1 t1 inner join db2.dbo.table2 t2 on T1.SomeID = T2.SomeID

    Edit: Or you might be able to parse it out of the query plan, if you're familiar with XML.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass