SQL exclude a column using SELECT * [except columnA] FROM tableA?

后端 未结 30 3392
花落未央
花落未央 2020-11-21 23:15

We all know that to select all columns from a table, we can use

SELECT * FROM tableA

Is there a way to exclude column(s) from a table witho

30条回答
  •  生来不讨喜
    2020-11-21 23:59

    The automated way to do this in SQL (SQL Server) is:

    declare @cols varchar(max), @query varchar(max);
    SELECT  @cols = STUFF
        (
            ( 
                SELECT DISTINCT '], [' + name
                FROM sys.columns
                where object_id = (
                    select top 1 object_id from sys.objects
                    where name = 'MyTable'
                )
                and name not in ('ColumnIDontWant1', 'ColumnIDontWant2')
                FOR XML PATH('')
            ), 1, 2, ''
        ) + ']';
    
    SELECT @query = 'select ' + @cols + ' from MyTable';  
    EXEC (@query);
    

提交回复
热议问题