Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 为什么我不能使用OBJECT_ID()函数找到外键?_Sql_Sql Server_Sql Server 2012 - Fatal编程技术网

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

Sql 为什么我不能使用OBJECT_ID()函数找到外键?,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,我在MS SQL Server 2012中遇到了一个奇怪的问题。我正在尝试检查升级脚本中是否已经存在外键。我以前使用过system 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 SELEC

我在MS SQL Server 2012中遇到了一个奇怪的问题。我正在尝试检查升级脚本中是否已经存在外键。我以前使用过system 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'

所以答案建议我的OBJECT_ID()查询应该可以工作。

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

SELECT OBJECT_ID(N'<schema>.FK_Name', N'F')
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

FK属于对象,而对象属于schemaDid我错过了一些东西,为什么是-1?你完全正确!在FK名称之前添加架构修复了它。谢谢这篇文章需要补充一点——如果外键名包含句号(.)字符,则必须将架构和名称放在方括号中,即[schema].[name]