Question

Why does full qualification appear to be getting ignored?

Here, I USE the database I'm querying, and get the expected results:

use [_DBMgt];
GO
select
    s.[name] as [Schema],
    o.[name] as [Table]
    from [_DBMgt].[sys].[objects] o
    inner join [_DBMgt].[sys].[schemas] s
        on s.[schema_id] = o.[schema_id]
    where OBJECTPROPERTY(o.[object_id], N'IsUserTable') = 1
    order by s.[name], o.[name]
;
GO

Schema Table
------ ---------------
dbo    TableAbbrLookup

(1 row(s) affected)

Here, I did not USE the database I intend to query, but fully qualify the database reference; however, I am not getting the expected results.

use [master];
GO
select
    s.[name] as [Schema],
    o.[name] as [Table]
    from [_DBMgt].[sys].[objects] o
    inner join [_DBMgt].[sys].[schemas] s
        on s.[schema_id] = o.[schema_id]
    where OBJECTPROPERTY(o.[object_id], N'IsUserTable') = 1
    order by s.[name], o.[name]
;
GO

Schema Table
------ ----------------------
sys    sqlagent_job_history
sys    sqlagent_jobsteps
sys    sqlagent_jobsteps_logs

(3 row(s) affected)

Either I'm expecting the wrong thing (likely) or I've found a bug (unlikely).

What am I missing?

Was it helpful?

Solution

From the documentation relating to OBJECTPROPERTY:

Remarks

The Database Engine assumes that object_id is in the current database context. A query that references an object_id in another database will return NULL or incorrect results. For example, in the following query the current database context is the master database. The Database Engine will try to return the property value for the specified object_id in that database instead of the database specified in the query. The query returns incorrect results because the view vEmployee is not in the master database.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top