选择带有通配符的列?

时间:2019-03-27 16:38:03

标签: sql select teradata

是否可以在Teradata中选择带有通配符的列?

赞:

Select ABC_* FROM TABLE;->在所有以ABC名称开头的列中得出结果。

1 个答案:

答案 0 :(得分:1)

虽然我与所有人都同意这是一个奇怪的要求,但并非完全没有听说过。不幸的是,在某些脚本之外,没有内置的SQL方法可以做到这一点。

这里的基本优点是,您不能通过SQL动态引用数据库对象(表,视图,过程,宏,函数,数据库,列等)。相反,您必须编写脚本来生成该SQL,然后执行该SQL,然后将结果返回给您。

尽管如此,我们可以使用存储过程直接在数据库中完成所有这些操作。

这是一个可以在Teradata中工作的简单示例(在将我们的yourdatabaseyourtable交换为您的实际数据库和表之后):

CREATE PROCEDURE return_tablecolumns_with_ABC()

/*
 * We have to tell teradata that this will return
 * a single result set
 */
DYNAMIC RESULT SETS 1
BEGIN   

    /*
     * We need three variables here
     * 1. A varchar to hold our list of columns from dbc.columnsV
     * 2. A varchar to hold the dynamically generated SQL string
     * 3. A cursor to hold the result set of the SQL string
     */
    DECLARE column_list VARCHAR(1000);    
    DECLARE my_sql VARCHAR(500);    
    DECLARE my_cursor CURSOR WITH RETURN ONLY FOR my_statement;

    /*
     * First we query dbc.columsV for a list of columns 
     *  that match your criteria (exists in your table and
     *  and starts with ABC_)
     */
    SELECT TRIM(TRAILING ',' FROM (XMLAGG(trim(ColumnName) || ',' ORDER BY ColumnName) (VARCHAR(1000)))) INTO column_list
    FROM "DBC"."ColumnsV" 
    WHERE DatabaseName = 'yourdatabase' 
        AND TableName = 'yourtable'
        AND columnName LIKE 'ABC_%';

    /* 
     * Now we build our dynamically generated SQL string
     * This could use some polish as it will fail if your
     * columns contain spaces or anything that requires 
     * their names be encapsulated with double quotes...
     */
    SET my_sql = 'Select ' || column_list || ' FROM yourdatabase.yourtable;';

    /*
     * Now we prepare our statement from the dynamically
     * generated SQL string
     */
    PREPARE my_statement FROM my_sql;

    /*
     * And finally we open the Cursor we declared for
     * the statement we just prepared. 
     * We leave the cursor open so it will be returned
     * as a result set when this procedure is called.
     */
    OPEN my_cursor;

END;

您现在可以调用它来获得结果:

CALL return_tablecolumns_with_ABC();