我有一个包含以下列的表attribute_config:
table_name column_name key
让我们说是低于2行
account accountphone accountnum
客户customernumber customerid
密钥只能是accountnum或customerid。
我必须编写接受的代码(i_accountnum,i_customerid)和;
使用where where条件中的键从table_name中提到的表中的column_name中提到的列中获取相应的值。
例如:从accountnum = i_accountnum的帐户中选择帐户电话 从customerid = i_customerid
的客户中选择customernumber应该动态形成完整的查询,无论是在查询中传递i_accountnum还是i_customerid还需要动态决定。如果密钥 - 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;
答案 0 :(得分: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时未声明的。