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

后端 未结 30 2522
花落未央
花落未央 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-22 00:09

    Yes it's possible (but not recommended).

    CREATE TABLE contact (contactid int, name varchar(100), dob datetime)
    INSERT INTO contact SELECT 1, 'Joe', '1974-01-01'
    
    DECLARE @columns varchar(8000)
    
    SELECT @columns = ISNULL(@columns + ', ','') + QUOTENAME(column_name)
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'contact' AND COLUMN_NAME <> 'dob'
    ORDER BY ORDINAL_POSITION
    
    EXEC ('SELECT ' + @columns + ' FROM contact')
    

    Explanation of the code:

    1. Declare a variable to store a comma separated list of column names. This defaults to NULL.
    2. Use a system view to determine the names of the columns in our table.
    3. Use SELECT @variable = @variable + ... FROM to concatenate the column names. This type of SELECT does not not return a result set. This is perhaps undocumented behaviour but works in every version of SQL Server. As an alternative you could use SET @variable = (SELECT ... FOR XML PATH('')) to concatenate strings.
    4. Use the ISNULL function to prepend a comma only if this is not the first column name. Use the QUOTENAME function to support spaces and punctuation in column names.
    5. Use the WHERE clause to hide columns we don't want to see.
    6. Use EXEC (@variable), also known as dynamic SQL, to resolve the column names at runtime. This is needed because we don't know the column names at compile time.

提交回复
热议问题