简体   繁体   中英

Select by column index number instead of column name in DB2

Is it possible to get the value of a column based on a column index? Something like the sql below:

SELECT 
    (SELECT colname 
     FROM syscat.columns 
     WHERE tabname = 'myTable' AND colno=100) AS TEST 
FROM myTable

The above sql returns only the column name of the specified index, not the actual value.

SQL is typed. The system needs to know which data type will be returned because there is a difference between a char(1), an integer and a BLOB type. Others have pointed out to use a stored procedure with dynamic SQL inside. However, even stored procedures have typed parameters. There are options to be relative generic for the parameters, but then those parameter structures have types attached.

What should work with functions and procedures is to

  1. retrieve the column name and data type, then
  2. prepare and execute a dynamic statement to process that desired column inside the function/procedure.

It's possible by using PureXML:

SELECT 
    XMLQUERY('$X[2]/text()'
        PASSING XMLCONCAT(
            XMLELEMENT(NAME "col1", first),
            XMLELEMENT(NAME "col2", middle),
            XMLELEMENT(NAME "col3", last) 
            --- . . .
            --- and so on
        ) AS "X"
    )
FROM employee

You change the xquery expression index number $X[ 2 ]/text() to access the wanted column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM