dynamic sql - Dynamically assigning variables oracle sql -
i have table attribute_config below columns:
table_name column_name key
let has below 2 rows
account accountphone accountnum
customer customernumber customerid
key can accountnum or customerid.
i have write code accept (i_accountnum,i_customerid) and;
fetch respective values columns mentioned in column_name in tables mentioned in table_name using key in condition.
for ex: select accountphone account accountnum = i_accountnum select customernumber customer customerid = i_customerid
the complete query should formed dynamically, whether pass i_accountnum or i_customerid in query needs decided dynamically. if key - accountnum, i_accountnum passed condition.
i have been trying on these lines far, not working, know wrong.
declare v_accountnum varchar2(20); v_customerid varchar2(20); v_attribute_value varchar2(20); v_stmt varchar2(255); begin account_num := 'testcustomer'; -- input function v_customer_ref := 'testaccount'; -- input function in (select * attribute_config) loop v_stmt := 'select ' || i.column_name || ' ' || i.table_name ||' ' || i.key|| ' = v_' || i.key; execute immediate v_stmt v_attribute_value; end loop; end;
this fix code, not see advantage of using dynamic query when code should accept 2 parameters(i_accountnum,i_customerid) - static situation , fetch relevant values, perhaps in learning purposes.
declare procedure fecth_values(i_accountnum account.accountnum%type, i_customerid customer.customerid%type) return varchar2 v_attribute_value varchar2(20); begin in (select * attribute_config) loop execute immediate 'select ' || i.column_name || ' ' || i.table_name || ' ' || i.key || ' = ' || case when i.key = 'accountnum' i_accountnum when i.key = 'customerid' i_customerid end; v_attribute_value; dbms_output.put_line(v_attribute_value); end loop; return null; end; begin fecth_values(1, 1); end;
your clause wrong i.key
should compared against inputed values, not 'v_' || i.key
, undeclared when execute stmt.
Comments
Post a Comment