1

我有一个表 attribute_config 以下列:

表名列名键

让我们说是有以下 2 行

帐号 帐号 电话 帐号

客户 customernumber customerid

密钥只能是 accountnum 或 customerid。

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

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

例如: select accountphone from account where accountnum = i_accountnum select customernumber from customer where customerid = i_customerid

完整的查询应该是动态形成的,查询中是否传递 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;
4

1 回答 1

0

这将修复您的代码,但是当您的代码应该接受 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 时未声明的 。

于 2014-11-27T12:50:26.877 回答