SQL Server 2012 上的可插入 UNION ALL VIEW

Insertable UNION ALL VIEW on SQL Server 2012

我提供了这个模式并且不可修改:

Table: Company1 Customers
+-------------+---------------+
| Customer ID | Customer Name |
+-------------+---------------+
| C0001       | ACME Inc.     |
| C0002       | Bogus Corp.   |
+-------------+---------------+

Table: Company2 Customers
+-------------+---------------+
| Customer ID | Customer Name |
+-------------+---------------+
| C0001       | Foo Bar Ltd.  |
| C0002       | John Smith    |
+-------------+---------------+

我需要这样的 insertable/updateable/deleteable 视图:

View: All Customers
+----------+-------------+---------------+
| Company  | Customer ID | Customer Name |
+----------+-------------+---------------+
| Company1 | C0001       | ACME Inc.     |
| Company1 | C0002       | Bogus Corp.   |
| Company2 | C0001       | Foo Bar Ltd.  |
| Company2 | C0002       | John Smith    |
+----------+-------------+---------------+

我将其构建为:

CREATE VIEW [All Customers] AS
   SELECT 'Company1' AS [Company], [Customer ID], [Customer Name]
   FROM [Company1_Customers]
UNION ALL
   SELECT 'Company2' AS [Company], [Customer ID], [Customer Name]
   FROM [Company2_Customers]

我如何(如果可能)告诉 SQL 服务器此视图中 [Company] = 'Company1' 属于 Company1_Customers[Company] = 'Company2' 的所有 INSERT/UPDATE/DELETE 操作属于 Company2_Customers?

here 你会看到

"Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table."

您的每个字段有两个基础 table,因为您的 UNION 所以此视图不能 "UPDATABLE"。

你最好的办法是修复你的架构并有一个 Customer table,其中 Company 作为列之一。您当前需要 UNION 才能完全查询的架构不是最好的。

您可以通过为 inserts/updates/deletes 创建一个 INSTEAD OF 触发器来做到这一点。

您可以检查 inserteddeleted 虚拟 table 以查看哪个 table 受到影响,并根据此执行正确的语句。 INSTEAD OF DELETE 触发器示例:

CREATE TRIGGER trigger_delete_all_customers ON [All Customers]
INSTEAD OF DELETE
AS
BEGIN
    DELETE c 
    FROM deleted AS d 
         INNER JOIN Company1_Customers AS c ON
              c.[Customer ID]=d.[Customer ID]
    WHERE
        d.[Company]='Company1';

    DELETE c 
    FROM deleted AS d 
         INNER JOIN Company2_Customers AS c ON
              c.[Customer ID]=d.[Customer ID]
    WHERE
        d.[Company]='Company2';
END

有关创建 INSTEAD OF 触发器的详细信息,请参阅 documentation