我在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'
解决方法
好吧,可能是你的外键正在寻找不在默认架构中的表(可能是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