SQL Server 2008 R2:通过删除特定表来更改视图

时间:2015-09-08 12:03:00

标签: sql-server sql-server-2008-r2

我有3个表,并为所有三个表创建了视图。

s1

CREATE TABLE s1
(
 Cola INT,
 Colb VARCHAR(10)
);

s2

CREATE TABLE s2
(
 Cola INT,
 Colb VARCHAR(10)
);

s3

CREATE TABLE s3
(
 Cola INT,
 Colb VARCHAR(10)
);

插入

INSERT INTO s1 VALUES(1,'a');
INSERT INTO s1 VALUES(1,'b');

INSERT INTO s2 VALUES(3,'c');
INSERT INTO s2 VALUES(4,'d');

INSERT INTO s3 VALUES(1,'a');
INSERT INTO s3 VALUES(1,'b');

创建视图sx

CREATE VIEW sx as
SELECT * FROM s1
UNION ALL 
SELECT * FROM s2
UNION ALL
SELECT * FROM s3;

现在我有了这个:

SELECT * FROM Sx;

结果

-------------
cola    colb
-------------
1       a
1       b
3       c
4       d
1       a
1       b

注意:我想要ALTER VIEW删除其中cola包含值1的表格。根据我的说法,表s1s3具有这些值。

注1 :如果所有表都包含值1,则VIEW必须为drop

问题:如何通过检查上面给出的具体条件来改变视图?

1 个答案:

答案 0 :(得分:0)

您可以使用替代触发器:

Create Trigger SX_Del On Sx Instead of delete
As 
Begin
    Delete s From s1 s Inner Join deleted d on d.Cola = s.Cola
    Delete From s2 Where cola in (Select Cola From deleted )
    Delete From s3 Where cola in (Select Cola From deleted )
End

就像您在视图中的每个不同的选择一样,您必须为每个表定义必须删除的内容。