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

前端之家收集整理的这篇文章主要介绍了sql – 为什么我不能使用OBJECT_ID()函数找到外键?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在MS sql Server 2012中有一个奇怪的问题.我正在尝试检查升级脚本中是否已存在外键.我过去使用系统OBJECT_ID()函数来查找表,视图和过程,但是当我尝试使用它来查找外键时它不起作用. @H_502_2@-- 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()查询应该有效.

解决方法

好吧,可能是你的外键正在寻找不在默认架构中的表(可能是dbo).在这种情况下,在指定模式之前,您将看不到object_id,如下所示: @H_502_2@SELECT OBJECT_ID(N'<schema>.FK_Name',N'F')

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

你可以像这样测试它:

@H_502_2@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

猜你在找的MsSQL相关文章