Dar*_*rel 7 sql sql-server sql-server-2012
我在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'
Run Code Online (Sandbox Code Playgroud)
这个 SO答案表明我的OBJECT_ID()查询应该有效.
Rom*_*kar 14
好吧,可能是你的外键正在寻找不在默认模式中的表(可能dbo).在这种情况下,object_id除非您指定架构,否则您将看不到:
SELECT OBJECT_ID(N'<schema>.FK_Name', N'F')
Run Code Online (Sandbox Code Playgroud)
实际上,您可以在数据库中使用多个具有相同名称的对象,但这些对象在不同的模式中.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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2899 次 |
| 最近记录: |