删除表格后刷新视图

时间:2019-05-22 04:27:43

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

我有下表:

系列一表:

create table tbl1
(
id int,
name varchar(100)
);
insert into tbl1 values(1,'tbl1');

create table tbl2
(
id int,
name varchar(100)
);
insert into tbl2 values(1,'tbl2');

create table tbl3
(
id int,
name varchar(100)
);
insert into tbl3 values(1,'tbl3');

create table tbl4
(
id int,
name varchar(100)
);
insert into tbl4 values(1,'tbl4');

系列双表:

create table tbl11
(
id int,
name varchar(100)
);
insert into tbl11 values(1,'tbl11');

create table tbl22
(
id int,
name varchar(100)
);
insert into tbl22 values(1,'tb22');

create table tbl33
(
id int,
name varchar(100)
);
insert into tbl33 values(1,'tbl33');

create table tbl44
(
id int,
name varchar(100)
);
insert into tbl44 values(1,'tbl44');

现在,我想为每个系列表创建VIEW

系列一视图:

create view View_tbl_one_series as 
select * from tbl1
union all
select * from tbl2
union all
select * from tbl3
union all
select * from tbl4

系列双人间:

create view View_tbl_double_series as 
select * from tbl11
union all
select * from tbl22
union all
select * from tbl33
union all
select * from tbl44

此后,我出于某种原因DROP TABLE tbl1并创建了另一个VIEW,其中包含两个序列视图的定义。

查看全部:

create view All_VIEW AS
select * from View_tbl_one_series
union all
select * from View_tbl_double_series

遇到错误:

  

消息208,级别16,状态1,过程View_tbl_one_series,第2行   无效的对象名称“ tbl1”。

尝试

exec sp_refreshview View_tbl_one_series

但仍然出现相同的错误。

注意:数据库系统中有很多tablesviews,创建视图全部是最后一个过程,在这两者之间必须删除一些表原因。

1 个答案:

答案 0 :(得分:0)

可以将SQL Server中的非物化视图视为该视图中基础表之上的薄包装。如果删除视图中涉及的一个或多个表,它将无法工作,因为无法再查询该表。这里有许多解决方法,其中一种方法是只创建索引(物化)视图:

CREATE VIEW View_tbl_one_series
WITH SCHEMABINDING
AS 
SELECT * from tbl1
UNION ALL
SELECT * from tbl2
UNION ALL
SELECT * from tbl3
UNION ALL
SELECT * from tbl4
GO
CREATE UNIQUE CLUSTERED INDEX idx ON View_tbl_one_series (id);

其他选项包括出于相同目的使用临时表,甚至可能是善意的常规表。

请注意,通常在联合查询中执行SELECT *并不理想,因为这可能会导致列/列类型可能无法在联合所涉及的两个表之间正确对齐的可能性。

相关问题