无法打开数据库,因为它处于脱机状态。但是它在 select 中已经被排除在外了。

Database cannot be opened because it is offline. But it is excluded allready in select..

我收到这个错误: 消息 942,级别 14,状态 4,第 2 行 数据库 'TESTNA' 无法打开,因为它处于脱机状态。

select name 
from sys.databases 
where state = 0  -- exclude offline databases
    and name <> db_name() -- exclude current dataase
    and OBJECT_ID (name+'.dbo.some_table','U') is not null  -- returns all   databases with some_table

我不明白。为什么会出现这个错误?数据库 TESTNA 被排除在条件 "state=0" 之外。

您可以在此处使用 case 表达式来解决 where 谓词的问题。像这样的东西应该可以做到。

select name, state 
from sys.databases 
where state = 0  -- exclude offline databases
    and name <> db_name() -- exclude current dataase
    and case when state = 0 then 
            case when OBJECT_ID (name+'.dbo.some_table','U') is not null then 1 end
        end = 1