TSQL foreign keys on views?

后端 未结 11 1083
臣服心动
臣服心动 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条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-01 14:21

    Peter already hit on this, but the best solution is to:

    1. Create the "main" logic (that filtering the referenced table) once.
    2. Have all views on related tables join to the view created for (1), not the original table.

    I.e.,

    CREATE VIEW v1 AS SELECT * FROM table1 WHERE blah
    
    CREATE VIEW v2 AS SELECT * FROM table2 WHERE EXISTS
      (SELECT NULL FROM v1 WHERE v1.id = table2.FKtoTable1)
    

    Sure, syntactic sugar for propagating filters for views on one table to views on subordinate tables would be handy, but alas, it's not part of the SQL standard. That said, this solution is still good enough -- efficient, straightforward, maintainable, and guarantees the desired state for the consuming code.

提交回复
热议问题