SQL Server 2012 上的可插入 UNION ALL VIEW
Posted
技术标签:
【中文标题】SQL Server 2012 上的可插入 UNION ALL VIEW【英文标题】:Insertable UNION ALL VIEW on SQL Server 2012 【发布时间】:2016-02-22 18:28:30 【问题描述】:我已提供此架构且不可修改:
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 |
+-------------+---------------+
我需要这样的可插入/可更新/可删除视图:
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 Server 在此视图中的所有 INSERT/UPDATE/DELETE 操作,其中[Company] = 'Company1'
属于Company1_Customers
,[Company] = 'Company2'
属于Company2_Customers
?
【问题讨论】:
If I update a view, will my original tables get updated的可能重复 【参考方案1】:您可以通过为插入/更新/删除创建一个INSTEAD OF
触发器来做到这一点。
您可以检查inserted
和deleted
虚拟表以查看受影响的表,并根据此执行正确的语句。 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。
【讨论】:
【参考方案2】:从here 你会看到
“任何修改,包括 UPDATE、INSERT 和 DELETE 语句, 必须只引用一个基表中的列。”
每个字段都有两个基表,因为您的UNION
所以这个视图不能是“UPDATABLE”。
您最好的办法是修复您的架构并拥有一个 Customer
表,其中 Company
作为列之一。您当前需要 UNION
才能完全查询的架构不是最好的。
【讨论】:
以上是关于SQL Server 2012 上的可插入 UNION ALL VIEW的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server 2008 在具有空间索引的可空地理列上的性能