【问题标题】:Why can I not find a foreign key using the OBJECT_ID() function?为什么使用 OBJECT_ID() 函数找不到外键?
【发布时间】:2015-04-16 16:07:39
【问题描述】:

我在 MS SQL Server 2012 中有一个奇怪的问题。我正在尝试检查升级脚本中是否已经存在外键。我过去使用系统 OBJECT_ID() 函数来查找表、视图和过程,但是当我尝试使用它来查找外键时,它不起作用。

-- This query always returns null
SELECT OBJECT_ID(N'FK_Name', N'F')

-- This query works, returning the object ID for the foreign key
SELECT object_id FROM sys.foreign_keys WHERE name=N'FK_Name'

This SO 答案表明我的 OBJECT_ID() 查询应该可以工作。

【问题讨论】:

    标签: sql sql-server sql-server-2012


    【解决方案1】:

    可能是您的外键正在查找不在默认模式中的表(可能是dbo)。在这种情况下,除非您指定架构,否则您不会看到 object_id,如下所示:

    SELECT OBJECT_ID(N'<schema>.FK_Name', N'F')
    

    实际上,您的数据库中可以有多个同名的对象,但在不同的模式中。 OBJECT_ID(N'FK_Name', N'F') 将在默认模式中返​​回对象的 id。

    你可以这样测试:

    create schema test
    create table test.temp1 (id int primary key)
    create table test.temp2 (id int)
    go
    
    alter table test.temp2 add constraint FK_temp foreign key(id) references test.temp1(id)
    
    select object_id('FK_temp', 'F')  -- returns null
    select object_id('test.FK_temp', 'F') -- returns object id
    
    drop table test.temp2
    drop table test.temp1
    drop schema test
    

    sql fiddle demo

    【讨论】:

    • FK属于对象,对象属于schema
    • 我错过了什么,为什么是-1?
    • 你说的完全正确!在 FK 名称之前添加架构修复了它。谢谢!
    • 要添加到这篇文章的一件事 - 如果外键名称包含句号 (.) 字符,您必须将架构和名称放在方括号中,即 [schema].[name]跨度>
    猜你喜欢
    • 1970-01-01
    • 2010-11-11
    • 2020-04-02
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多