我最近在我的核心业务表上添加了一列,这个表作为一张统计视图的基表。加完这一列后,我在视图上运行新版本的统计应用,却发现新加的列没有出现在我的结果集中。
我的表和视图如下:
create table Customer ( customer_id int not null primary key, firstname varchar(40) not null, lastname varchar(40) not null, birthdate datetime null ); insert into Customer (customer_id,firstname, lastname, birthdate) values(1,'George', 'Washington', '1950-07-01') ; insert into Customer (customer_id,firstname, lastname, birthdate) values(2,'James', 'Madison', '1948-11-09') ; insert into Customer (customer_id,firstname, lastname, birthdate) values(3,'Alexander', 'Hamilton', '1970-03-02') ; create view v_Customer as select * from Customer ; /*变更前统计视图的数据*/ select * from v_customer ; +-------------+-----------+------------+---------------------+ | customer_id | firstname | lastname | birthdate | +-------------+-----------+------------+---------------------+ | 1 | George | Washington | 1950-07-01 00:00:00 | | 2 | James | Madison | 1948-11-09 00:00:00 | | 3 | Alexander | Hamilton | 1970-03-02 00:00:00 | +-------------+-----------+------------+---------------------+ /*更新基表结构*/ alter table Customer add last_order_date datetime; /*变更后统计视图的数据*/ select * from v_customer ; +-------------+-----------+------------+---------------------+ | customer_id | firstname | lastname | birthdate | +-------------+-----------+------------+---------------------+ | 1 | George | Washington | 1950-07-01 00:00:00 | | 2 | James | Madison | 1948-11-09 00:00:00 | | 3 | Alexander | Hamilton | 1970-03-02 00:00:00 | +-------------+-----------+------------+---------------------+
我使用select *创建视图,为什么基表结构变了,视图不跟着变呢?
本题来源mssqltips
虽然视图创建时是使用select *,但是其元数据创建后是固定的,包括列数量,名称,类型等。我们可以查看其结构:
desc v_customer; +-------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+-------+ | customer_id | int | NO | | NULL | | | firstname | varchar(40) | NO | | NULL | | | lastname | varchar(40) | NO | | NULL | | | birthdate | datetime | YES | | NULL | | +-------------+-------------+------+-----+---------+-------+
所以基表添加列,但是视图依然只选择定义中的这几列而已,自然不会出现新列的数据。要更新视图,最直接的方式是删除drop后重建create。
另外,使用select *的方式来创建view本身就不推荐,参看这篇为什么说程序中使用select *是有害的?
The post 表结构变了,视图结构却没有更新 appeared first on SQLParty.