gpt4 book ai didi

sql - View 上的 TSQL 外键?

转载 作者:行者123 更新时间:2023-12-02 01:56:22 25 4
gpt4 key购买 nike

我有一个 SQL-Server 2008 数据库和一个使用外键约束来强制引用完整性的架构。按预期工作。现在,用户在原始表上创建 View 以仅处理数据的子集。我的问题是,过滤某些表中的某些数据集而不是其他表中的数据集将违反外键约束。
想象两个表“一”和“二”。 “one”仅包含一个值为 1、2、3 的 id 列。 “二”指的是“一”。现在您在两个表上创建 View 。表“二”的 View 不会过滤任何内容,而表“一”的 View 会删除除第一行之外的所有行。您最终会在第二个 View 中看到无处可去的条目。

有什么办法可以避免这种情况吗? View 之间可以有外键约束吗?

一些澄清回应一些评论:
我知道即使通过 View 插入,底层约束也将确保数据的完整性。我的问题在于消耗 View 的语句。这些语句是在考虑原始表的情况下编写的,并假设某些连接不会失败。在使用表时,这个假设始终有效 - 但 View 可能会破坏它。
由于存在大量引用表,因此在创建 View 时首先连接/检查所有约束非常麻烦。因此我希望避免这种情况。

最佳答案

我喜欢你的问题。它对查询优化器非常熟悉,以及它如何看到某些连接没有任何用途,或者如果知道连接的另一侧最多有一个命中,它可以简化某些操作,那么它们是多余的。

因此,最大的问题是您是否可以针对索引 View 的 CIX 进行 FK。答案是否定的。

create table dbo.testtable (id int identity(1,1) primary key, val int not null);
go
create view dbo.testview with schemabinding as
select id, val
from dbo.testtable
where val >= 50
;
go
insert dbo.testtable
select 20 union all
select 30 union all
select 40 union all
select 50 union all
select 60 union all
select 70
go
create unique clustered index ixV on dbo.testview(id);
go
create table dbo.secondtable (id int references dbo.testview(id));
go

除了最后一条语句之外,所有这些都有效,该语句错误如下:

Msg 1768, Level 16, State 0, Line 1
Foreign key 'FK__secondtable__id__6A325CF7' references object 'dbo.testview' which is not a user table.

因此外键必须引用用户表。

但是...下一个问题是关于是否可以引用在 SQL 2008 中过滤的唯一索引,以实现类似 View 的 FK。

答案仍然是否定的。

create unique index ixUV on dbo.testtable(val) where val >= 50;
go

成功了。

但是现在如果我尝试创建一个引用 val 列的表

create table dbo.thirdtable (id int identity(1,1) primary key, val int not null check (val >= 50) references dbo.testtable(val));

(我希望与过滤索引中的过滤器匹配的检查约束可以帮助系统理解 FK 应该保持)

但我收到一条错误消息:

There are no primary or candidate keys in the referenced table 'dbo.testtable' that matching the referencing column list in the foreign key 'FK__thirdtable__val__0EA330E9'.

如果我删除过滤索引并创建一个未过滤的唯一非聚集索引,那么我可以毫无问题地创建 dbo.thirdtable。

所以恐怕答案似乎仍然是否定的。

关于sql - View 上的 TSQL 外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1928355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com