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

SELECT * FROM tableA

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

SELECT * [except columnA] FROM tableA

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


当前回答

您可以使用REGEX列规范。

下面的查询选择除ds和hr之外的所有列 选择(ds |人力资源)? +。+来自销售

其他回答

Postgres sql有一种方法

请参考: http://www.postgresonline.com/journal/archives/41-How-to-SELECT-ALL-EXCEPT-some-columns-in-a-table.html

信息Schema Hack方法

SELECT 'SELECT ' || array_to_string(ARRAY(SELECT 'o' || '.' || c.column_name
        FROM information_schema.columns As c
            WHERE table_name = 'officepark' 
            AND  c.column_name NOT IN('officeparkid', 'contractor')
    ), ',') || ' FROM officepark As o' As sqlstmt

对于我的特定示例表,上面的代码生成如下所示的sql语句

选择o.officepark、o.owner o.squarefootage 从办公室公园As o

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

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.

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

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

这就给了你剩下的cols

我这样做了,它工作得很好(版本5.5.41):

# prepare column list using info from a table of choice
SET @dyn_colums = (SELECT REPLACE(
GROUP_CONCAT(`COLUMN_NAME`), ',column_name_to_remove','') 
FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE 
`TABLE_SCHEMA`='database_name' AND `TABLE_NAME`='table_name');

# set sql command using prepared columns
SET @sql = CONCAT("SELECT ", @dyn_colums, " FROM table_name");

# prepare and execute
PREPARE statement FROM @sql;
EXECUTE statement;

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

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