【问题标题】:Dynamically assigning variables oracle sql动态分配变量oracle sql
【发布时间】:2014-11-27 11:51:52
【问题描述】:

我有一个表属性配置以下列:

table_name column_name key

假设是 2 行以下

帐号帐号电话帐号

客户 customernumber customerid

Key 只能是 accountnum 或 customerid。

我必须编写可以接受 (i_accountnum,i_customerid) 的代码,并且;

使用 where 条件中的键从 table_name 中提到的表中 column_name 中提到的列中获取相应的值。

例如:从 accountnum = i_accountnum 的帐户中选择 accountphone 从 customerid = i_customerid 的客户中选择 customernumber

完整的查询应该是动态形成的,查询中是否传递i_accountnum或i_customerid也需要动态决定。 if key - accountnum, i_accountnum 将传递给 where 条件。

到目前为止,我一直在尝试这些线路,这不起作用,我知道这是错误的。

declare
v_accountnum varchar2(20);
v_customerid varchar2(20);
v_attribute_value varchar2(20);
v_stmt varchar2(255);
begin
Account_Num := 'TestCustomer';  -- input to the function
v_customer_ref := 'TestAccount'; -- input to the function
for i in (Select * from attribute_config) loop
v_stmt := 'select ' || i.column_name || ' from ' ||  i.table_name ||' where ' || i.key|| ' = v_' || i.key;
execute immediate v_Stmt into v_attribute_value;
end loop;
end;

【问题讨论】:

    标签: oracle dynamic-sql execute-immediate


    【解决方案1】:

    这将修复您的代码,但是当您的代码应该接受 2 个参数(i_accountnum,i_customerid)时,我看不到使用动态查询的任何优势 - 这已经是静态情况并获取相关值,可能仅用于学习目的。

    declare
       procedure fecth_values(i_accountnum account.accountnum%type,
                              i_customerid customer.customerid%type) return varchar2 is
          v_attribute_value varchar2(20);
       begin
          for i in (select * from attribute_config) loop
             execute immediate 'select ' || i.column_name || ' from ' ||
                               i.table_name || ' where ' || i.key || ' = ' || case when i.key = 'accountnum' then i_accountnum when i.key = 'customerid' then i_customerid end;
             into v_attribute_value;
             dbms_output.put_line(v_attribute_value);
          end loop;
          return null;
       end;
    begin
       fecth_values(1, 1);
    end;
    

    您的 where 子句错误,应将 i.key 与输入的值进行比较,而不是 'v_' || i.key,后者在您执行 stmt 时未声明。

    【讨论】:

    • 我想要实现的是为 where 条件动态准备密钥。
    • 未来可能会有不同的key,比如productid,然后那个key会在table中配置,where条件应该执行'where i_productid ='。关于接受 2 个参数的函数,虽然它接受 2 个参数,但要查询表,总是使用 1 个参数,我想动态决定(使用 i.key)使用哪个参数。现在是 i_accountnum 或 i_customerid,将来可能是 i_productid。不是case语句,如何使用i_key本身判断参数并传递给动态sql?
    • 改变你的方法。创建一个接收table namekey value 的函数。使用 table name 参数从映射表中映射相关键列名称和获取参数并返回该值。根据需要调用此函数 2 次、3 次。
    • 不明白你想说什么。不过,CASE 声明很有帮助,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多