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

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 without specifying all the columns?

SELECT * [except columnA] FROM tableA

The only way that I know is to manually specify all the columns and exclude the unwanted column. This is really time consuming so I'm looking for ways to save time and effort on this, as well as future maintenance should the table has more/less columns.

thanks!


我同意每个人......但如果我要做这样的事情,我可以这样做:

/* Get the data into a temp table */
SELECT * INTO #TempTable
FROM YourTable
/* Drop the columns that are not needed */
ALTER TABLE #TempTable
DROP COLUMN ColumnToDrop
/* Get results and drop temp table */
SELECT * FROM #TempTable
DROP TABLE #TempTable

No.

Maintenance-light best practice is to specify only the required columns.

At least 2 reasons:

  • This makes your contract between client and database stable. Same data, every time
  • Performance, covering indexes
  • Edit (July 2011):

    If you drag from Object Explorer the Columns node for a table, it puts a CSV list of columns in the Query Window for you which achieves one of your goals


    在SQL(SQL Server)中执行此操作的自动方法是:

    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);
    
    链接地址: http://www.djcxy.com/p/93838.html

    上一篇: 如何在运行时在C#中获取表的列名?

    下一篇: SQL使用SELECT *排除列[[除了columnA] FROM tableA?