oraclepython使用Select Result作为列名

2024-09-30 08:18:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在python中使用cx-oracle模块。我有两张这样的桌子:

第一张桌子:

|  parameter   |   context  |
+--------------+------------+
|      a       |  column_1  | 
|      b       |  column_2  |

第二名:

|id|  column_1      |  column_2   |
+--+----------------+-------------+
| 1|  bla1          |  (NULL)     | 
| 2|  bla2          |  (NULL)     | 
| 3|  (NULL)        |  (nla1)     | 
| 4|  (NULL)        |  (nla2)     | 

输入为: a, nla1如果我想从第二个表返回id = 3,那么如何创建查询呢?你知道吗

表结构已经是这样了。我不能改变它。你知道吗


Tags: 模块idparametercontextcolumn结构nulloracle
2条回答

"the column_name is variable it can be column1 if parameter a but can be column2 if parameter b"

用常规SQL编写这样的语句是不可能的:您需要使用动态的,这意味着PL/SQL。Find out more。你知道吗

简单的实现是这样的:

create or replace function get_id is
     (p_param_col in varchar2
      , p_param_val in varchar2)
    return number
is
    l_col_name varchar2(30);
    return_value number;
begin
    select context into l_col_name
    from table_1
    where parameter = p_param_col;

    execute immediate 'select id from table_2 where '
            || l_col_name || ' = :1'
         into return_value
         using p_param_val;

   return return_value;
end;

使用动态SQL在运行时设计查询,然后执行IMMEDIATE子句。你知道吗

相关问题 更多 >

    热门问题