问题
I am trying to insert data whose schema is dynamic, as in user enters the schema name. For some reason I get ORA-000942: table doesn't exist
even though table is there in the correct schema.
Here is the code:
declare
l_ext_files_names varchar2(4000) := '&1';
l_schema_name varchar2(4000) := '&2';
l_table_name varchar2(4000) := l_schema_name||'.files_tbl';
l_int_files_names varchar2(4000);
c_file_name sys_refcursor;
begin
open c_file_name for 'select file_names from '||l_table_name;
loop
fetch c_file_name into l_int_files_names;
if (l_int_files_names <> l_ext_files_names) then
insert into l_table_name (file_names, status)
values (l_files_names, 'done');
end if;
end loop;
close c_file_name;
end;
Any idea where I am making the mistake? Cheers in advance :)
回答1:
Most probably the user
doesn't have the privilege
to access the table in other schema.
You would need to grant the SELECT
privilege.
GRANT SELECT ON table_name TO username;
Put the required table_name
and in username
put the user which is executing the SELECT.
回答2:
After some researches and strolling trough the internet, this is what I found. It seems that I need to declare the schema and table names variables in a slightly different way. Why this solution works? no idea.
declare
l_schema_name all_tables.owner%type := '&1';
l_ext_files_names varchar2(4000) := '&2';
l_table_name all_tables.table_name%type := 'FILES_TBL';
l_int_files_names varchar2(4000);
c_file_name sys_refcursor;
begin
open c_file_name for 'select file_names from '||l_schema_name||'.'||l_table_name;
fetch c_file_name into l_int_files_names;
if c_file_name%notfound then
execute immediate 'insert into '||l_schema_name||'.'||l_table_name||' (file_names, entry, status) values ('''||l_ext_files_names||''', sysdate, ''done'')';
commit;
elsif (l_int_files_names <> l_ext_files_names) then
execute immediate 'insert into '||l_schema_name||'.'||l_table_name||' (file_names, entry, status) values ('''||l_ext_files_names||''', sysdate, ''done'')';
commit;
else
dbms_output.put_line ('Already there.');
end if;
exception when others then
dbms_output.put_line ('Some errors.');
end;
/
来源:https://stackoverflow.com/questions/31182880/dynamic-table-name-in-cursor