我们都知道,要从表中选择所有列,可以使用

SELECT * FROM tableA

是否有一种方法可以在不指定所有列的情况下从表中排除列?

SELECT * [except columnA] FROM tableA

我所知道的唯一方法是手动指定所有列并排除不需要的列。这真的很耗时,所以我正在寻找方法来节省时间和精力,以及未来的维护表应该有更多/更少的列。


当前回答

我知道这个问题很老了,但我希望这仍然能对你有所帮助。答案来自于SQL Server论坛的一个讨论。您可以将其设置为存储过程。还可以修改它以添加多个except字段。

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

其他回答

是的,这是可能的(但不建议)。

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')

代码说明:

Declare a variable to store a comma separated list of column names. This defaults to NULL. Use a system view to determine the names of the columns in our table. 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. 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. Use the WHERE clause to hide columns we don't want to see. 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.

右键单击对象资源管理器中的表,选择前1000行

它会列出所有列,而不是*。然后删除不需要的列。应该比你自己打快多了。

然后,当你觉得这有点太多的工作,获得Red Gate的SQL提示,并从tbl输入ssf,转到*并再次单击选项卡。

在Hive Sql中,你可以这样做:

set hive.support.quoted.identifiers=none;
select 
    `(unwanted_col1|unwanted_col2|unwanted_col3)?+.+`
from database.table

这就给了你剩下的cols

这样做不是更简单吗:

sp_help <table_name>

点击“Column_name”列>复制>粘贴(创建一个垂直列表)到新建查询窗口,只需在每个列值前面键入逗号…注释掉你不想要的专栏。比这里提供的任何代码都要少得多,而且仍然是可管理的。

不,这是不可能的。如果在您的情况下可行,也许您可以创建自定义视图

如果你的数据库支持动态sql的执行,你可以写一个SP,把你不想看到的列传递给它,让它动态创建查询并返回结果给你。我认为这至少在SQL Server中是可行的