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

后端 未结 30 2549
花落未央
花落未央 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:43

    In summary you cannot do it, but I disagree with all of the comment above, there "are" scenarios where you can legitimately use a * When you create a nested query in order to select a specific range out of a whole list (such as paging) why in the world would want to specify each column on the outer select statement when you have done it in the inner?

    0 讨论(0)
  • 2020-11-21 23:43

    I know this is a little old, but I had just run into the same issue and was looking for an answer. Then I had a senior developer show me a very simple trick.

    If you are using the management studio query editor, expand the database, then expand the table that you are selecting from so that you can see the columns folder.

    In your select statement, just highlight the referenced columns folder above and drag and drop it into the query window. It will paste all of the columns of the table, then just simply remove the identity column from the list of columns...

    0 讨论(0)
  • 2020-11-21 23:43

    I know this question is old, but I hope this can still be helpful.The answer is inspired by a discuss from SQL Server Forums. You can make this a stored procedure. It can also be modified to add more than one except fields.

    DECLARE @SQL NVARCHAR(MAX)
    SELECT @SQL = COALESCE(@SQL + ', ', ' ' ) + name from sys.columns where name not in ('colName1','colName2') and object_id = (Select id from sysobjects where name = 'tblName')
    SELECT @SQL = 'SELECT ' + @SQL + ' FROM ' + 'tblName'
    EXEC sp_executesql  @SQL
    
    0 讨论(0)
  • 2020-11-21 23:45

    I do not know of any database that supports this (SQL Server, MySQL, Oracle, PostgreSQL). It is definitely not part of the SQL standards so I think you have to specify only the columns you want.

    You could of course build your SQL statement dynamically and have the server execute it. But this opens up the possibility for SQL injection..

    0 讨论(0)
  • 2020-11-21 23:46

    Right click table in Object Explorer, Select top 1000 rows

    It'll list all columns and not *. Then remove the unwanted column(s). Should be much faster than typing it yourself.

    Then when you feel this is a bit too much work, get Red Gate's SQL Prompt, and type ssf from tbl, go to the * and click tab again.

    0 讨论(0)
  • 2020-11-21 23:52

    no there is no way to do this. maybe you can create custom views if that's feasible in your situation

    EDIT May be if your DB supports execution of dynamic sql u could write an SP and pass the columns u don't want to see to it and let it create the query dynamically and return the result to you. I think this is doable in SQL Server atleast

    0 讨论(0)
提交回复
热议问题