I'm currently using this code to generate an XLS file from a query in Oracle PL/SQL saving a file with HTML tags using this code.
CREATE OR REPLACE PROCEDURE GENERATE_XLS(querie VARCHAR2) IS
v_file VARCHAR2 (20) := 'TEST-EXCEL.xls';
v_directory VARCHAR2 (60) := 'C:\';
p_write LIB_FILES.file_type;
v_sql varchar2(32767) := 'SELECT LASTNAME, NAME, ID
FROM DUAL';
header VARCHAR(1000) := '<html> <head><center><B><U> TEST XLS </U></B></center>
<table></tr><tr><th>LASTNAME</th><th>NAME</th><th>ID</th></tr>';
BEGIN
p_write := LIB_FILES.fopen (v_directory, v_file, 'W');
LIB_FILES.put_line (p_write, header);
FOR REGISTRY IN querie LOOP
LIB_FILES.put_line (p_write,'<tr><td>'||REGISTRY.LASTNAME||'</td><td>'||REGISTRY.NAME||'</td><td>'||REGISTRY.ID||'</td></tr>');
END LOOP;
LIB_FILES.put_line (p_write,'</table>');
LIB_FILES.fflush (p_write);
LIB_FILES.fclose (p_write);
END;
This is working right now, but I need to add to this procedure a parameter, which is an SQL query, and then generate the file based on the query
I'm currently use this code to get the columns name
CREATE OR REPLACE PROCEDURE GET_COLUMNS IS
v_cursor_id integer;
v_col_cnt integer;
v_columns dbms_sql.desc_tab;
v_sql varchar2(3000) :='SELECT LASTNAME, NAME, ID FROM DUAL';
header VARCHAR(1000):='<html> <head><center><B><U> TEST XLS </U></B></center>
<table></tr><tr>';
begin
v_cursor_id := dbms_sql.open_cursor;
dbms_sql.parse(v_cursor_id, v_sql, dbms_sql.native);
dbms_sql.describe_columns(v_cursor_id, v_col_cnt, v_columns);
for i in 1 .. v_columns.count loop
header := header || '<th>'|| v_columns(i).col_name ||'</th>';
end loop;
header := header || '</tr>';
dbms_sql.close_cursor(v_cursor_id);
exception when others then
dbms_sql.close_cursor(v_cursor_id);
raise;
end;
But here I'm facing the same issue, I need to make this procedures works with dynamic queries coming from a parameter instead of declaring the query in the procedure.
How can I achieve this?
I don't have oracle installed , as of my knowledge I gave these details ... check and verify this
CREATE OR REPLACE PROCEDURE GET_COLUMNS (p_sql IN VARCHAR2 , p_header IN VARCHAR2)
IS
v_cursor_id integer;
v_col_cnt integer;
v_columns dbms_sql.desc_tab;
v_sql varchar2(3000) := p_sql;
header VARCHAR(1000):= p_header;
begin
v_cursor_id := dbms_sql.open_cursor;
dbms_sql.parse(v_cursor_id, v_sql, dbms_sql.native);
dbms_sql.describe_columns(v_cursor_id, v_col_cnt, v_columns);
for i in 1 .. v_columns.count loop
header := header || '<th>'|| v_columns(i).col_name ||'</th>';
end loop;
header := header || '</tr>';
dbms_sql.close_cursor(v_cursor_id);
exception when others then
dbms_sql.close_cursor(v_cursor_id);
raise;
end;
To execute
Execute GET_COLUMNS ('SELECT LASTNAME, NAME, ID FROM DUAL','<html> <head><center><B><U> TEST XLS </U></B></center>
<table></tr><tr>');
If you define your query as a ref cursor instead of a string, e.g.
open your_refcursor for select * from dual;
then you can convert it to a dbms_sql cursor ID using
v_cursor_id := dbms_sql.to_cursor_number(your_refcursor);
Here is one I wrote earlier:
http://www.williamrobertson.net/documents/refcursor-to-csv.shtml
I suggest read the following article, about a package to create Excel files from Oracle:
Create an Excel-file with PL/SQL
Related
I am writing a stored procedure where I have to do following: I want to have a file (any format properties, json, xml) which will have information of which columns I want to extract from my table.
For example: my table has columns A,B,C,D,E, and suppose my file.properties has below information
A=1
B=0
C=1
D=1
F=0
So my generated query should be Select A,C,D from my table;
How can I do this in Oracle 11G?
I think you need this
SQL> set serveroutput on;
SQL> create or replace procedure pr_dynamic_sql( v_result out sys_refcursor ) is
v_outfile utl_file.file_type;
v_path varchar2(100) := 'UTL_FILE_DIR';
-- alias for the directory where your text files generated at OS.
v_row varchar2(100);
v_file varchar2(100);
v_letter varchar2(10);
v_number varchar2(10);
v_sql varchar2(100):= 'select ';
begin
v_file := 'myfile.properties';
v_outfile := utl_file.fopen(v_path, v_file, 'r');
loop
begin
utl_file.get_line(v_outfile,v_row);
v_letter := regexp_substr(v_row,'[^=]');
v_number := substr(regexp_substr(v_row,'[^=]+$'),1,1);
if v_number = '1' then
v_sql := v_sql||v_letter||',';
end if;
exception when no_data_found then exit;
end;
end loop;
utl_file.fclose(v_outfile);
v_sql := rtrim(v_sql,',')||' from mytable';
open v_result for v_sql;
end;
and call
SQL> begin
pr_dynamic_sql(v_result => :v_result);
end;
/
to get results as of cursor type.
Background
I'm trying to make a re-usable PL/SQL procedure to move data from one
database to another.
For this purpose, I'm using dynamic SQL.
The procedure executes perfectly if I use a REPLACE with placeholders.
However, for security reasons, I want to use bind variables.
Question
How can I make an entire PL/SQL code block dynamic (with bind
variables)? If I use a REPLACE instead of the bind variables, it works
fine.
How to replicate
To replicate this in your database, create the following procedure as it is:
create or replace procedure move_data(i_schema_name in varchar2, i_table_name in varchar2, i_destination in varchar2) as
l_sql varchar2(32767);
l_cursor_limit pls_integer := 500;
l_values_list varchar2(32767);
begin
select listagg('l_to_be_moved(i).' || column_name, ', ') within group (order by column_id)
into l_values_list
from all_tab_cols
where owner = i_schema_name and
table_name = i_table_name and
virtual_column = 'NO';
l_sql := q'[
declare
l_cur_limit pls_integer := :l_cursor_limit;
cursor c_get_to_be_moved is
select :i_table_name.*, :i_table_name.rowid
from :i_table_name;
type tab_to_be_moved is table of c_get_to_be_moved%rowtype;
l_to_be_moved tab_to_be_moved;
begin
open c_get_to_be_moved;
loop
fetch c_get_to_be_moved
bulk collect into l_to_be_moved limit l_cur_limit;
exit when l_to_be_moved.count = 0;
for i in 1.. l_to_be_moved.count loop
begin
insert into :i_table_name#:i_destination values (:l_values_list);
exception
when others then
dbms_output.put_line(sqlerrm);
l_to_be_moved.delete(i);
end;
end loop;
forall i in 1.. l_to_be_moved.count
delete
from :i_table_name
where rowid = l_to_be_moved(i).rowid;
for i in 1..l_to_be_moved.count loop
if (sql%bulk_rowcount(i) = 0) then
raise_application_error(-20001, 'Could not find ROWID to delete. Rolling back...');
end if;
end loop;
commit;
end loop;
close c_get_to_be_moved;
exception
when others then
rollback;
dbms_output.put_line(sqlerrm);
end;]';
execute immediate l_sql using l_cursor_limit, i_table_name, i_destination, l_values_list;
exception
when others then
rollback;
dbms_output.put_line(sqlerrm);
end;
/
And then you can execute the procedure with the following:
begin
move_data('MySchemaName', 'MyTableName', 'MyDatabaseLinkName');
end;
/
Due to many reasons(inability to generate an appropriate execution plan, security checking, etc.) Oracle does not allow identifiers binding (table names, schema names, column names and so on). So if it's really necessary, the only way is to hard code those identifiers after some sort of validation (to prevent SQL injection).
If I understand well, you could try a trick, by using a dynamic SQL inside a dynamic SQL.
setup:
create table tab100 as select level l from dual connect by level <= 100;
create table tab200 as select level l from dual connect by level <= 200;
create table tabDest as select * from tab100 where 1 = 2;
This will not work:
create or replace procedure testBind (pTableName in varchar2) is
vSQL varchar2(32000);
begin
vSQL := 'insert into tabDest select * from :tableName';
execute immediate vSQL using pTableName;
end;
But this will do the trick:
create or replace procedure testBind2 (pTableName in varchar2) is
vSQL varchar2(32000);
begin
vSQL := q'[declare
vTab varchar2(30) := :tableName;
vSQL2 varchar2(32000) := 'insert into tabDest select * from ' || vTab;
begin
execute immediate vSQL2;
end;
]';
execute immediate vSQL using pTableName;
end;
I think you can do it simpler.
create or replace procedure move_data(i_schema_name in varchar2, i_table_name in varchar2, i_destination in varchar2) as
l_sql varchar2(32767);
begin
select listagg('l_to_be_moved(i).' || column_name, ', ') within group (order by column_id)
into l_values_list
from all_tab_cols
where owner = i_schema_name and
table_name = i_table_name and
virtual_column = 'NO';
l_sql := 'insert into '||i_destination||'.'||i_table_name||' select * from '||i_schema_name||'.'||i_table_name;
execute immediate l_sql;
end;
If you are concerned about SQL-Injection, have a look at package DBMS_ASSERT. This PL/SQL package provides function to validate properties of input values.
I've been looking at the DBMS_SQL package in Oracle and trying to see if there is a way to create a view or something that users can select from to see the results of a dynamic SQL query.
I have a test procedure based on the documentation:
CREATE OR REPLACE PROCEDURE test_dyn_sql AS
cursor_name INTEGER;
rows_processed INTEGER;
l_query LONG;
BEGIN
l_query := 'SELECT SYSDATE AS the_date, ''ABC'' AS the_string, 1 AS the_int FROM dual';
cursor_name := dbms_sql.open_cursor;
DBMS_SQL.PARSE(cursor_name, l_query, DBMS_SQL.NATIVE);
rows_processed := DBMS_SQL.EXECUTE(cursor_name);
DBMS_SQL.CLOSE_CURSOR(cursor_name);
EXCEPTION
WHEN OTHERS THEN
DBMS_SQL.CLOSE_CURSOR(cursor_name);
DBMS_OUTPUT.put_line('ERROR');
END;
But this just executes the statement and does not return anything. What I'd like is a view so a user can just do a SELECT the_date FROM some_view and get the results. I will not know the names or number of columns in advance, so that's why I'm after a dynamic SQL solution.
" I will not know the names or number of columns in advance, so that's
why I'm after a dynamic SQL solution"
That's pretty hard to implement in SQL: SQL is all about the data structures, and it really expects the columns to exist up front. So you cannot build a VIEW on a mutable data structure.
You can implement a function which returns a ref cursor. This is a pointer to a data structure which can be interpreted by a client, say as a JDBC ResultSet.
Here's an example function which takes a table name and column name, assembles the query and returns its result set.
CREATE OR REPLACE FUNCTION test_dyn_sql
(tab_name in varchar2
, col_name in varchar2)
return sys_refcursor
AS
return_value sys_refcursor;
BEGIN
open return_value for
'SELECT SYSDATE AS the_date, '||col_name||' FROM '||tab_name;
return return_value;
END;
/
The output is not very elegant in SQL*Plus but you get the idea.
SQL> select test_dyn_sql ('EMP', 'NAME') from dual;
TEST_DYN_SQL('EMP','
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
THE_DATE NAME
--------- ------------------------------
03-APR-15 FOX IN SOCKS
03-APR-15 MR KNOX
03-APR-15 DAISY-HEAD MAYZIE
SQL>
I suggest you stick with Native Dynamic SQL (that is, execute immediate) as much as possible: as you can see, it's really simple compared to DBMS_SQL. Only reach for DBMS_SQL when you have some extremely complicated requirement.
I appreciate this may not be the solution form you're looking for. If that is the case please edit your question to provide more details about the problem you're trying to solve.
If you want your code to return the value of rows_processed variable use the code below which will return 0.
CREATE OR REPLACE FUNCTION test_dyn_sql(asd INTEGER) RETURN INTEGER AS
cursor_name INTEGER;
rows_processed INTEGER;
l_query LONG;
BEGIN
l_query := 'SELECT SYSDATE AS the_date, ''ABC'' AS the_string, 1 AS the_int FROM dual';
cursor_name := dbms_sql.open_cursor;
DBMS_SQL.PARSE(cursor_name, l_query, DBMS_SQL.NATIVE);
rows_processed := DBMS_SQL.EXECUTE(cursor_name);
DBMS_SQL.CLOSE_CURSOR(cursor_name);
RETURN rows_processed;
EXCEPTION
WHEN OTHERS THEN
DBMS_SQL.CLOSE_CURSOR(cursor_name);
DBMS_OUTPUT.put_line('ERROR');
RETURN 0;
END;
This is how you call the function from plsql
DECLARE
rows_precessed INTEGER;
BEGIN
rows_precessed := test_dyn_sqll(0);
DBMS_OUTPUT.put_line(rows_precessed);
END;
Trying to execute a procedure dynamically with DBMS_SQL that takes 'table of varchar' and sys_refcursor as an argument using the code below:
DECLARE
TYPE CriteriaMap IS TABLE OF VARCHAR (100)
INDEX BY VARCHAR2 (100);
o_cursor SYS_REFCURSOR;
v_cid INTEGER;
v_dummy INTEGER;
v_date_to_run DATE := SYSDATE;
v_sql_execute_proc VARCHAR2 (1024);
v_filter_criteria CriteriaMap;
BEGIN
v_sql_execute_proc :=
'begin MY_PROCEDURE(:v_date_to_run, :filter_criteria, :o_cursor); end;';
v_cid := DBMS_SQL.open_cursor;
DBMS_SQL.parse (v_cid, v_sql_execute_proc, DBMS_SQL.native);
DBMS_SQL.bind_variable (v_cid, 'v_date_to_run', v_date_to_run);
DBMS_SQL.bind_variable (v_cid, 'filter_criteria', v_filter_criteria);
DBMS_SQL.bind_variable (v_cid, 'o_cursor', o_cursor);
v_dummy := DBMS_SQL.execute (v_cid);
DBMS_SQL.close_cursor (v_cid);
END;
as the result the following error is thrown
Error report:
ORA-06550: line 14, column 3:
PLS-00306: wrong number or types of arguments in call to 'BIND_VARIABLE'
Documentation http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_sql.htm says that BIND_VARIABLE takes only a limited number of data types and 'table of varchar' and sys_refcursor are not in the list.
Is there any workaround to pass arguments to a dynamic function which data types are not in the list?
table of varchar is suppoorted through bind_array (though it has to be as per the spec in dbms_sql which is indexed by integer and not varchar2).
can you explain more on why you're using dynamic SQL in this case? as your example does not warrant dynamic SQL as the structure of the call is fixed here.
I know it's old... but if anyone encounters this - it is possible (in 11g, not sure about earlier) to convert the sys ref cursor to a cursor number, bind it, and then transform it to a refcursor after the execute - something like:
declare
vSQL varchar2(1000) := 'declare
v_rc sys_refcursor;
begin
open v_rc for select ''this is a test'' from dual;
:v_cursor_number := dbms_sql.to_cursor_number(v_rc);
end;';
v_rc sys_refcursor;
v_cursor_number NUMBER;
v_cur number;
v_result number;
vFetchValue varchar2(20);
begin
--open the cursor
v_cur := DBMS_SQL.OPEN_CURSOR;
--parse
DBMS_SQL.PARSE(v_cur, vSQL, dbms_sql.native);
--bind the cursor number
DBMS_SQL.BIND_VARIABLE(v_cur, 'v_cursor_number', v_cursor_number);
--execute
v_result := DBMS_SQL.EXECUTE(v_cur);
-- get back the value of the bind cursor number
DBMS_SQL.VARIABLE_VALUE(v_cur,'v_cursor_number', v_cursor_number);
--transform it to a standard sys_refcursor
v_rc := DBMS_SQL.TO_REFCURSOR (v_cursor_number);
--close the cursor
DBMS_SQL.CLOSE_CURSOR(v_cur);
fetch v_rc into vFetchValue;
close v_rc;
dbms_output.put_line(vFetchValue);
end;
/
I am writing a procedure to create a CSV file with the data in an Oracle table. I used "spool filename;" but an error is coming. Can I use spool in PL/SQL?
I think that there are better ways to implement this on Oracle 10g/11g, but this should work fine on Oracle 9i or higher:
CREATE OR REPLACE PROCEDURE prc_file_mult_column_generate(
p_file_dir VARCHAR2, -- mandatory (Oracle directory name)
p_file_name VARCHAR2, -- mandatory
p_sql_query VARCHAR2, -- Multiple column SQL SELECT statement that needs to be executed and processed
p_delimiter CHAR -- column delimiter
)
AS
l_cursor_handle INTEGER;
l_dummy NUMBER;
l_col_cnt INTEGER;
l_rec_tab DBMS_SQL.DESC_TAB;
l_current_col NUMBER(16);
l_current_line VARCHAR2(2047);
l_column_value VARCHAR2(300);
l_file_handle UTL_FILE.FILE_TYPE;
l_print_text VARCHAR2(100);
l_record_count NUMBER(16) := 0;
BEGIN
/* Open file for append*/
l_file_handle := UTL_FILE.FOPEN(p_file_dir, p_file_name, 'a', 2047); --Append Mode, 2047 chars per line max, possibly increasable
l_cursor_handle := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(l_cursor_handle, p_sql_query, DBMS_SQL.native);
l_dummy := DBMS_SQL.EXECUTE(l_cursor_handle);
/* Output column names and define them for latter retrieval of data */
DBMS_SQL.DESCRIBE_COLUMNS(l_cursor_handle, l_col_cnt, l_rec_tab); -- get column names
/* Append to file column headers */
l_current_col := l_rec_tab.FIRST;
IF (l_current_col IS NOT NULL) THEN
LOOP
DBMS_SQL.DEFINE_COLUMN(l_cursor_handle, l_current_col, l_column_value, 300);
l_print_text := l_rec_tab(l_current_col).col_name || p_delimiter;
UTL_FILE.PUT (l_file_handle, l_print_text);
l_current_col := l_rec_tab.NEXT(l_current_col);
EXIT WHEN (l_current_col IS NULL);
END LOOP;
END IF;
UTL_FILE.PUT_LINE (l_file_handle,' ');
/* Append data for each row */
LOOP
EXIT WHEN DBMS_SQL.FETCH_ROWS(l_cursor_handle) = 0; -- no more rows to be fetched
l_current_line := '';
/* Append data for each column */
FOR l_current_col IN 1..l_col_cnt LOOP
DBMS_SQL.COLUMN_VALUE (l_cursor_handle, l_current_col, l_column_value);
l_print_text := l_column_value || p_delimiter;
l_current_line := l_current_line || l_column_value || p_delimiter;
END LOOP;
l_record_count := l_record_count + 1;
UTL_FILE.PUT_LINE (l_file_handle, l_current_line);
END LOOP;
UTL_FILE.FCLOSE (l_file_handle);
DBMS_SQL.CLOSE_CURSOR(l_cursor_handle);
EXCEPTION
WHEN OTHERS THEN
-- Release resources
IF DBMS_SQL.IS_OPEN(l_cursor_handle) THEN
DBMS_SQL.CLOSE_CURSOR(l_cursor_handle);
END IF;
IF UTL_FILE.IS_OPEN (l_file_handle) THEN
UTL_FILE.FCLOSE (l_file_handle);
END IF;
--RAISE ;
DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.format_error_stack);
END;
/
spool is a sqlplus command. it cannot be used in pl/sql.
it seems that you have been trying a variety of ways to get oracle to do your formatting and file saving. why not have your program that is calling the proc do this work for you?
If you only need the data in a cvs file you can do this:
create a sql file with the query like this:
set feedback off verify off heading off pagesize 0
select field1 || ',' || field2 ... from table;
quit;
/
then call sqlplus from a terminal like this:
sqlplus -S user/password #file.sql> cvsfile.cvs
No, SPOOL is a SQL Plus command so you would have to do this in SQL Plus:
spool myfile.txt
exec myproc
spool off
You would probably also need to set some values before starting the process e.g.
set pagesize 0 linesize 1000 trimspool on
... to get the correct formatting.
Here are a couple of links you might find helpful:
A PL/SQL Tutorial and SQL*Plus User Guide (11g)
Creating an ascii file: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:459020243348 and http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:68212348056 and http://www.oracle-developer.net/display.php?id=425 .