What is the reason not to use select *?

后端 未结 20 3135
独厮守ぢ
独厮守ぢ 2020-11-21 07:14

I\'ve seen a number of people claim that you should specifically name each column you want in your select query.

Assuming I\'m going to use all of the columns anyway

20条回答
  •  不要未来只要你来
    2020-11-21 08:11

    I actually noticed a strange behaviour when I used select * in views in SQL Server 2005.

    Run the following query and you will see what I mean.

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[starTest]') AND type in (N'U'))
    DROP TABLE [dbo].[starTest]
    CREATE TABLE [dbo].[starTest](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [A] [varchar](50) NULL,
        [B] [varchar](50) NULL,
        [C] [varchar](50) NULL
    ) ON [PRIMARY]
    
    GO
    
    insert into dbo.starTest
    select 'a1','b1','c1'
    union all select 'a2','b2','c2'
    union all select 'a3','b3','c3'
    
    go
    IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vStartest]'))
    DROP VIEW [dbo].[vStartest]
    go
    create view dbo.vStartest as
    select * from dbo.starTest
    go
    
    go
    IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vExplicittest]'))
    DROP VIEW [dbo].[vExplicittest]
    go
    create view dbo.[vExplicittest] as
    select a,b,c from dbo.starTest
    go
    
    
    select a,b,c from dbo.vStartest
    select a,b,c from dbo.vExplicitTest
    
    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[starTest]') AND type in (N'U'))
    DROP TABLE [dbo].[starTest]
    CREATE TABLE [dbo].[starTest](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [A] [varchar](50) NULL,
        [B] [varchar](50) NULL,
        [D] [varchar](50) NULL,
        [C] [varchar](50) NULL
    ) ON [PRIMARY]
    
    GO
    
    insert into dbo.starTest
    select 'a1','b1','d1','c1'
    union all select 'a2','b2','d2','c2'
    union all select 'a3','b3','d3','c3'
    
    select a,b,c from dbo.vStartest
    select a,b,c from dbo.vExplicittest
    

    Compare the results of last 2 select statements. I believe what you will see is a result of Select * referencing columns by index instead of name.

    If you rebuild the view it will work fine again.

    EDIT

    I have added a separate question, *“select * from table” vs “select colA, colB, etc. from table” interesting behaviour in SQL Server 2005* to look into that behaviour in more details.

提交回复
热议问题