SQL Server的情况实际上比@ user12861的答案还要糟糕,这意味着:如果对多个表使用SELECT *
,向查询中早期引用的表添加列实际上会导致您的视图返回在旧列的幌子下的新列。看下面的例子:
-- create two tables
CREATE TABLE temp1 (ColumnA INT, ColumnB DATE, ColumnC DECIMAL(2,1))
CREATE TABLE temp2 (ColumnX INT, ColumnY DATE, ColumnZ DECIMAL(2,1))
GO
-- populate with dummy data
INSERT INTO temp1 (ColumnA, ColumnB, ColumnC) VALUES (1, '1/1/1900', 0.5)
INSERT INTO temp2 (ColumnX, ColumnY, ColumnZ) VALUES (1, '1/1/1900', 0.5)
GO
-- create a view with a pair of SELECT * statements
CREATE VIEW vwtemp AS
SELECT *
FROM temp1 INNER JOIN temp2 ON 1=1
GO
-- SELECT showing the columns properly assigned
SELECT * FROM vwTemp
GO
-- add a few columns to the first table referenced in the SELECT
ALTER TABLE temp1 ADD ColumnD varchar(1)
ALTER TABLE temp1 ADD ColumnE varchar(1)
ALTER TABLE temp1 ADD ColumnF varchar(1)
GO
-- populate those columns with dummy data
UPDATE temp1 SET ColumnD = 'D', ColumnE = 'E', ColumnF = 'F'
GO
-- notice that the original columns have the wrong data in them now, causing any datatype-specific queries (e.g., arithmetic, dateadd, etc.) to fail
SELECT *
FROM vwtemp
GO
-- clean up
DROP VIEW vwTemp
DROP TABLE temp2
DROP TABLE temp1
请检查我的其他评论,在SQL Server上所有的变化不一定被接受。 – user12861 2008-11-04 23:03:57
此外,使用视图的代码不应该使用*,所以在视图中使用*可能是相当合理的,并且使用视图的代码将使用视图来确保它不使用*。 – 2008-11-06 03:52:43
最后的评论是完全错误的(至少在sql server中) - 发生相反情况 - 对基础表的更改将被忽略。这是@ user12861提到的。在sql server中,任何使用select *的视图都需要在underyling表发生变化时删除并重新创建,否则它将默默无法显示所有列。这是一种非常糟糕的失败形式,因为它不太可能在开发环境中得到提升,因为您定期从头开始重建数据库。在添加列时,忘记删除并重建表格上的所有视图也非常容易 – 2015-04-22 11:27:15