When using oracle SQL is it possible to run a query based on a text_string from a subquery? An example might clarify what I\'m trying to do
select count(sql_
Generally, this isn't a particularly good design-- storing SQL in tables and dynamically executing it introduces all sorts of security and maintenance issues.
It is probably possible (though it's way too late on a Friday that started way too early for me to try to figure it out) to do a really cool XML query along the lines of this query that runs a count(*) against every table in the schema that would do this all in one query.
For the vast majority of programmers, though, the simpler approach would be to loop over the queries, run them one at a time, and store the results somewhere. Potentially the local variable would be added to a collection of counts, for example.
FOR q IN (SELECT sql_text FROM query_table)
LOOP
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM (' || q.sql_text || ')'
INTO some_local_variable;
<<do something with the local variable>>
END LOOP;
Since you're trying to create a view, you could take this logic and put it in a pipelined table function. You'd do a PIPE ROW
to return data within the loop. Your view could then be created on top of the pipelined table function.
You can do it in PL/SQL, it can look like this (if I understand your requirement properly):
create table sql_commands (cmd varchar2(1000));
insert into sql_commands values ('select * from table_1');
insert into sql_commands values ('select * from table_2');
commit;
declare
begin
for aLine in (select cmd from sql_commands) loop
execute immediate aLine.cmd into ... -- depends on your command
end loop;
end;
Going through Basics..
When the database executes an SQL
1) It would first do SEMANTIC
check by validating the syntax and the objects (tables and columns used) in SQL.
2) Based on it, the optimizer
draws a PLAN
(calculating the indexes to be used, with the available table statistics and histograms)..
3) And the SQL Engine
executes the Query as per the PLAN.
So, all these means, the SQL cannot do dynamic object referings.. Since it needs to study all the elements in SQL before execution itself.
Hence, unfortunately, your requirement is NOT possible with a simple SQL solution.
PL/SQL
or some other Database specific special tools.. is what you have to opt for.