且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么使用 OBJECT_ID() 函数找不到外键?

更新时间:2023-11-10 18:37:16

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

Well it could be that your foreign key is looking to the table not in default schema (probably dbo). In this case you'll not see object_id until you specify schema, like this:

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

实际上,您的数据库中可以有多个具有相同名称的对象,但它们位于不同的架构中.OBJECT_ID(N'FK_Name', N'F') 将返回默认模式中对象的 id.

Actually, you could have multiple objects with the same name in your database, but within different schemas. OBJECT_ID(N'FK_Name', N'F') will return id of object in the default schema.

你可以这样测试:

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 小提琴演示