TSQL foreign keys on views?

后端 未结 11 1086
臣服心动
臣服心动 2021-01-01 13:51

I have a SQL-Server 2008 database and a schema which uses foreign key constraints to enforce referential integrity. Works as intended. Now the user creates views on the orig

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 14:43

    I love your question. It screams of familiarity with the Query Optimizer, and how it can see that some joins are redundant if they serve no purpose, or if it can simplify something knowing that there is at most one hit on the other side of a join.

    So, the big question is around whether you can make a FK against the CIX of an Indexed View. And the answer is no.

    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
    

    All this works except for the last statement, which errors with:

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

    So the Foreign key must reference a user table.

    But... the next question is about whether you could reference a unique index that is filtered in SQL 2008, to achieve a view-like FK.

    And still the answer is no.

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

    This succeeded.

    But now if I try to create a table that references the val column

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

    (I was hoping that the check constraint that matched the filter in the filtered index might help the system understand that the FK should hold)

    But I get an error saying:

    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'.
    

    If I drop the filtered index and create a non-filtered unique non-clustered index, then I can create dbo.thirdtable without any problems.

    So I'm afraid the answer still seems to be No.

提交回复
热议问题