Why is using '*' to build a view bad?

后端 未结 14 2158
执念已碎
执念已碎 2020-11-27 07:02

Why is using \'*\' to build a view bad ?

Suppose that you have a complex join and all fields may be used somewhere.

Then you just have to chose fields needed

14条回答
  •  渐次进展
    2020-11-27 07:47

    The situation on SQL Server is actually even worse than the answer by @user12861 implies: if you use SELECT * against multiple tables, adding columns to a table referenced early in the query will actually cause your view to return the values of the new columns under the guise of the old columns. See the example below:

    -- 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
    

提交回复
热议问题