FOPEN, UTL_FILE. Put_line - how
I'm trying to execute the PL/SQL block to write a Union query results to a file (called vFILE). The output I'm generating a requirements of special format given to me by my Bank, because it is a store file. I created the formatting in the part of the execution of sql select. How can I this fits in the FOPEN, UTL_FILE. Put_line and FCLOSE commands? Or I have to do something completely different? Note: There are 3 parts to the Union - part 1 query is the header, part 2 is the detail, and part 3 is the trailer. Thank you!That's what the output in the file should look like:
HCORP123 08112009 (header)
R00000123450000277057000010000001282009SA (retail)
R00000123450000277058000020000001282009SA (retail)
R00000123450000277059000010000008062009SA (retail)
T000001234500000000030000000400000 (trailer)
DECLARE
vFile UTL_FILE. TYPE_DE_FICHIER;
BEGIN
vFile: = UTL_FILE. FOPEN ('/ devlop, e001, usc, pospay', 'POSPAY_USC2.txt', 'w', 32767);
FOR x IN)
SELECT
'H'||
RPAD ('USC2 ', 33,' ') |
TO_CHAR ((SYSDATE), 'MMDDYYYY') |
LPAD (", 70,' ')
Of
DOUBLE
UNION ALL
SELECT
'R'||
LPAD ((b.BANK_ACCOUNT_NUM), 10, '0').
LPAD ((a.CHECK_NUMBER), 10, '0').
LPAD ((a.amount*100), 10, '0').
To_char ((a.CHECK_DATE), 'MMDDYYYY') |
MAX (DECODE (UPPER (a.STATUS_LOOKUP_CODE),
"NEGOTIABLE", "SA"
'ISSUED', 'SA ',.
"ERASED", "SA"
"DISABLED BUT STILL MISSING", "SA"
"RECONCILED", "SA"
"EMPTY',"MS. "
"CONFIGURATION", "SP",.
"OVERFLOW", "SP",.
"SPOILED,", "SP", "SA")) |
RPAD ((a.VENDOR_NAME), 71,' ')
Of
USCAP. AP_CHECKS_ALL has,
USCAP. AP_BANK_ACCOUNTS_ALL b
WHERE
b.BANK_ACCOUNT_ID = a.BANK_ACCOUNT_ID and
b.BANK_ACCOUNT_NAME = a.BANK_ACCOUNT_NAME and
a.POSITIVE_PAY_STATUS_CODE = "UNSENT" AND
b.BANK_ACCOUNT_ID = 10063
GROUP BY
b.BANK_ACCOUNT_NUM, a.CHECK_NUMBER, a.AMOUNT, a.CHECK_DATE, a.VENDOR_NAME
UNION ALL
SELECT
'T'||
LPAD ((b.BANK_ACCOUNT_NUM), 10, '0').
LPAD ((Count (a.CHECK_ID)), 10, '0').
LPAD ((Sum(a.amount*100)), 13, '0')
Of
USCAP. AP_CHECKS_ALL has,
USCAP. AP_BANK_ACCOUNTS_ALL b
WHERE
b.BANK_ACCOUNT_ID = a.BANK_ACCOUNT_ID and
b.BANK_ACCOUNT_NAME = a.BANK_ACCOUNT_NAME and
b.BANK_ACCOUNT_ID = 10063
GROUP BY b.BANK_ACCOUNT_NUM;
)
LOOP
UTL_FILE. Put_line (vFile, x.item1, x.item2,?,?);
END LOOP;
UTL_FILE. FCLOSE (vFile);
END;
Hello
Interplay says:
Hi Frank,.
I'm a newbie in the forums, and I don't know how other people are able to post / paste formatted code. I type in it and at the time of publication, the formatting is removed. Can you let me know how you could get the "x.item1 | x.Item2' to look like it was stuck in?
I typed these 6 characters
(1) left-brace,
(2) the letter c,
(3) the letter o,
(4) the letter d,
(5) the letter e, and
(6) right curly - support, i.e.:
{code}
exactly as see you above, before this line and again after this line.
I know how to do the basic put_line function. I can do with a statement SELECT simple from a table when selecting few fields, but this situation is more complex because it is a UNION query that has a header line, multiline retail, and on the line of the trailer. I have included the example of the output formatting that I am doing in the first post, just to illustrate the final result, that I'm looking. If I run the SQL SELECT * more, it looks good, but I try to use the command put_line (because I'm using PL/SQL) to write this same layout in a file.
Regardless of whether or not the query is a UNION: the mechanics are the same. Make sure that each column you select has a unique name, so you can reference it later. Only the name (or alias) since the first part of the UNION really matters, but it is good programming practice to explicitly assign the same alias in all branches of the UNION, like this:
FOR x IN (
SELECT 'H' ||
RPAD('USC2',33,' ') ||
TO_CHAR((SYSDATE), 'MMDDYYYY') ||
LPAD(' ',70,' ') AS txt
FROM DUAL
UNION ALL
SELECT 'R' ||
LPAD((b.BANK_ACCOUNT_NUM),10,'0') ||
LPAD((a.CHECK_NUMBER),10,'0') ||
LPAD((a.AMOUNT*100),10,'0') ||
TO_CHAR((a.CHECK_DATE), 'MMDDYYYY') ||
MAX ( CASE WHEN UPPER (a.STATUS_LOOKUP_CODE) IN ( 'VOIDED'
, 'SETUP'
, 'OVERFLOW'
, 'SPOILED,'
)
THEN 'SP'
ELSE 'SA'
END
) ||
RPAD((a.VENDOR_NAME),71,' ') AS txt
FROM
USCAP.AP_CHECKS_ALL a,
USCAP.AP_BANK_ACCOUNTS_ALL b
WHERE
b.BANK_ACCOUNT_ID = a.BANK_ACCOUNT_ID AND
b.BANK_ACCOUNT_NAME = a.BANK_ACCOUNT_NAME AND
a.POSITIVE_PAY_STATUS_CODE = 'UNSENT' AND
b.BANK_ACCOUNT_ID = 10063
GROUP BY b.BANK_ACCOUNT_NUM,
a.CHECK_NUMBER,
a.AMOUNT,
a.CHECK_DATE,
a.VENDOR_NAME
UNION ALL
SELECT 'T' ||
LPAD((b.BANK_ACCOUNT_NUM),10,'0') ||
LPAD((COUNT(a.CHECK_ID)),10,'0') ||
LPAD((SUM(a.AMOUNT*100)),13,'0') AS txt
FROM
USCAP.AP_CHECKS_ALL a,
USCAP.AP_BANK_ACCOUNTS_ALL b
WHERE
b.BANK_ACCOUNT_ID = a.BANK_ACCOUNT_ID and
b.BANK_ACCOUNT_NAME = a.BANK_ACCOUNT_NAME and
b.BANK_ACCOUNT_ID = 10063
GROUP BY b.BANK_ACCOUNT_NUM -- No ; here
)
LOOP
UTL_FILE.PUT_LINE (vFile, x.txt);
END LOOP;
In the example above, there are 3 pins to the UNION. Each has 1 column in the SELECT clause, and this column is always called txt. When you need to refer to this column, use the cursor name, followed by a dot, followed by the name of the column: x.txt.
Furthermore, you should not have an ORDER BY clause? Without one, there is no guarantee that the header will come first, or even related to the bank_account_num lines will be together.
Appears not to work-"during the validation of code (or any formatted text) on this site, type the 6 characters (small letters only, inside curly braces) before and after the section of text formatted, to keep the spacing" see below... "
SELECT
{abce, abcd}
Of
{a.table}
Sorry, I don't know what you mean here. Looks like you are trying to put something else the magic word 'code' inside the braces. Do not. The only thing inside the braces must be the 4 letter word 'code', which must be all lowercase.
Tags: Database
Similar Questions
-
Hello
We try to generate a flat file from an Oracle table through utl_file.put_line. He is troubled with the Fed line of character. How deal with him or another way to do this?
Any suggestions are greatly appreciated.
Thank you.
JimmyI assume that your database is running on unix/linux?
Try to use UTL_FILE. PUT (Data), followed by a UTL_FILE. PUT (CHR (13): 10;)
-
UTL_FILE.put_line cannot insert all rows
As shown in the code below, I have for loops with the entrails of IF ELSE statement. How am I suppose to retrieve all rows in my csv file as currently, the csv file has only the last line inserted in the file?
for c7_rec in C7 loop FOR C8_REC IN C8(c7_rec.PASSPORTNO) LOOP if l_loop8 = 0 then CASE SIGN(C8_REC.AMOUNT) -- check amount negative or positive. If negative need refund to customer else customer owe starhub WHEN -1 THEN l_negative:=1; l_amount_negative:= C8_REC.AMOUNT; DBMS_OUTPUT.PUT_LINE(l_amount_negative); ELSE l_positive:=1; l_amount_positive:= C8_REC.AMOUNT; DBMS_OUTPUT.PUT_LINE(l_amount_positive); END case; IF l_positive=1 AND l_negative=1 THEN IF l_amount_positive < abs(l_amount_negative) then DBMS_OUTPUT.PUT_LINE('Positive smaller than negative'); --l_amount_total:= l_amount_positive+l_amount_negative; utl_file.put_line(l_file,c8_rec.CUSTOMER_ID || ' ' ||C8_REC.CUSTOMER_ID|| ' ' ||l_amount_positive|| ' ' ||c8_rec.ohstatus); Elsif l_amount_positive > abs(l_amount_negative) THEN DBMS_OUTPUT.PUT_LINE('Positive bigger than negative'); ELSE DBMS_OUTPUT.PUT_LINE('Nothing to offset'); END IF; --DBMS_OUTPUT.PUT_LINE(c8_rec.CUSTOMER_ID || ' ' ||C8_REC.CUSTOMER_ID|| ' ' ||C8_REC.AMOUNT|| ' ' ||c8_rec.ohstatus); --|| ' ' ||i.cscurbalance); l_loop8:=1; elsIF l_positive=1 AND l_negative=0 THEN --l_amount_total:= l_amount_positive+l_amount_negative; utl_file.put_line(l_file,c8_rec.CUSTOMER_ID || ' ' ||C8_REC.CUSTOMER_ID|| ' ' ||l_amount_positive|| ' ' ||c8_rec.ohstatus); l_loop8:=1; elsIF l_positive=0 AND l_negative=1 THEN --l_amount_total:= l_amount_positive+l_amount_negative; utl_file.put_line(l_file,c8_rec.CUSTOMER_ID || ' ' ||C8_REC.CUSTOMER_ID|| ' ' ||l_amount_negative|| ' ' ||c8_rec.ohstatus); l_loop8:=1; END IF; --DBMS_OUTPUT.PUT_LINE(C11_REC.AMOUNT||' '||C11_REC.PASSPORTNO||' '||C11_REC.OHSTATUS); end if; END LOOP; l_positive:=0; l_negative:=0; END LOOP; utl_file.fclose( l_file );
CREATE OR REPLACE Procedure p_lee_test As Cursor C7 Is Select Unique Passportno From j_lee_test; Cursor C8(p_Passportno12 Varchar2) Is Select Unique Passportno, Customer_Id, Case When Min_Sign = Max_Sign Then Sum(amt) Over(Partition By Passportno Order By Passportno) Else amt End Amount, Ohstatus From (Select Passportno, Customer_Id, amt, Min(Sign(amt)) Over(Partition By Passportno Order By Passportno) Min_Sign, Max(Sign(amt)) Over(Partition By Passportno Order By Passportno) Max_Sign, Ohstatus From j_lee_test Where Passportno = p_Passportno12) Order By 1; l_Loop7 Integer := 0; l_Loop8 Integer := 0; l_Positive Integer := 0; l_Negative Integer := 0; l_File Utl_File.File_Type; l_Date Date := Sysdate; l_Amount_Positive Float; l_Amount_Negative Float; l_Amount_Total Float; Begin /*l_File := Utl_File.Fopen('UTL_TMP_DIR', 'ZERORISATION_' || To_Char(l_Date, 'YYYYMMDD') || '.csv', 'w');*/ l_file := Utl_File.Fopen('/export/orautil/loguser/utl', 'ZERORISATION_' || To_Char(l_Date, 'YYYYMMDD') || '.csv', 'w'); For C7_Rec In C7 Loop For C8_Rec In C8(C7_Rec.Passportno) Loop -- If l_Loop8 = 0 Then Case Sign(C8_Rec.Amount) -- check amount negative or positive. If negative need refund to customer else customer owe starhub When -1 Then l_Negative := 1; l_Amount_Negative := C8_Rec.Amount; Dbms_Output.Put_Line(l_Amount_Negative); Else l_Positive := 1; l_Amount_Positive := C8_Rec.Amount; Dbms_Output.Put_Line(l_Amount_Positive); End Case; If l_Positive = 1 And l_Negative = 1 Then If l_Amount_Positive < Abs(l_Amount_Negative) Then Dbms_Output.Put_Line('Positive smaller than negative'); --l_amount_total:= l_amount_positive+l_amount_negative; Utl_File.Put_Line(l_File, C8_Rec.Customer_Id || ' ' || C8_Rec.Customer_Id || ' ' || l_Amount_Positive || ' ' || C8_Rec.Ohstatus); Elsif l_Amount_Positive > Abs(l_Amount_Negative) Then Dbms_Output.Put_Line('Positive bigger than negative'); Else Dbms_Output.Put_Line('Nothing to offset'); End If; --DBMS_OUTPUT.PUT_LINE(c8_rec.CUSTOMER_ID || ' ' ||C8_REC.CUSTOMER_ID|| ' ' ||C8_REC.AMOUNT|| ' ' ||c8_rec.ohstatus); --|| ' ' ||i.cscurbalance); l_Loop8 := 1; Elsif l_Positive = 1 And l_Negative = 0 Then --l_amount_total:= l_amount_positive+l_amount_negative; Utl_File.Put_Line(l_File, C8_Rec.Customer_Id || ' ' || C8_Rec.Customer_Id || ' ' || l_Amount_Positive || ' ' || C8_Rec.Ohstatus); l_Loop8 := 1; Elsif l_Positive = 0 And l_Negative = 1 Then --l_amount_total:= l_amount_positive+l_amount_negative; Utl_File.Put_Line(l_File, C8_Rec.Customer_Id || ' ' || C8_Rec.Customer_Id || ' ' || l_Amount_Negative || ' ' || C8_Rec.Ohstatus); l_Loop8 := 1; End If; --DBMS_OUTPUT.PUT_LINE(C11_REC.AMOUNT||' '||C11_REC.PASSPORTNO||' '||C11_REC.OHSTATUS); -- End If; End Loop; l_Positive := 0; l_Negative := 0; End Loop; Utl_File.Fclose(l_File); End; 47817 47817 -.13 CO117587 117587 -17.5 CO240012 240012 -43.9 CM47265 47265 -489.76 IN47265 47265 220.24 DP your l_Loop8 = 0 for first time, but for other times its always 1...
-
For loop - utl_file.put_line
I have this loop which I want to put the conditions as follows:
How am I suppose to do?for rec in C3(i.customer_id,i.co_id) = 'DP' and = 'CO') --conditions here loop utl_file.put_line( l_file,'Status is '||c3_rec.ohstatus|| ' ' ||i.co_id); end loop; -- DBMS_OUTPUT.PUT_LINE('Status is '||c3_rec.ohstatus|| ' ' ||i.co_id); END IF; utl_file.fclose( l_file );
Published by: JoannaLee on August 27, 2008 19:47You don't want to open and close the file within the loop. It is extremely inefficient, the more it will overwrite data in the file each time that perform you an iteration in the loop (you can open the file in Add mode, rather than write mode, to solve the problem of the crash, but you would still have the performance issue).
You want that the code looks like
-- Open file l_file := utl_file.fopen( ... ); -- Loop over your cursor FOR c3_rec IN C3(i.customer_id,i.co_id) LOOP -- Write a row to the file utl_file.put_line( ... ); END LOOP; -- Close the file utl_file.fclose( ... );
For simplicity, I am omitting exception handling logic, but I hope you see the general approach.
Justin
-
PLSQL utl_file.put_line error after the script running 8 ' e
Hello
I wrote a script to export the results of a query to an external file using utl_file.put_line. the script works very well for the first 8 hours.
anonymous block filled
anonymous block filled
anonymous block filled
anonymous block filled
anonymous block filled
anonymous block filled
anonymous block filled
anonymous block filled
When I run the same script for the 9th time, I got an error message
Error from the 1 in the command line:
DECLARE
OutFile utl_file.file_type;
TYPE rc_a IS REF CURSOR;
l_rc_a rc_a;
TELLER_1 INTEGER: = 3;
ctt1 varchar (2000);
AA varchar (2000);
BEGIN
FOR TELLER_1 IN 3.9
LOOP
OutFile: = utl_file.fopen ('DAT_DIR', 'A1_W' |) TELLER_1 | "_KANS. TXT', 'w');
ctt1: = '
SELECT
WORP_XW | ''|''||
D | ''|''||
V5_AANTAL_KANS | ''|''||
V5_AVG_KANS | ''|''||
V6_AANTAL_KANS | ''|''||
V6_AVG_KANS | ''|''||
V7_AANTAL_KANS | ''|''||
V7_AVG_KANS | ''|''||
V8_AANTAL_KANS | ''|''||
V8_AVG_KANS | ''|''||
V9_AANTAL_KANS | ''|''||
V9_AVG_KANS
Of
(
Select D, V5_AANTAL_KANS, V5_AVG_KANS, V6_AANTAL_KANS, WORP_XW, ROUND(V6_AVG_KANS,6) V6_AVG_KANS ROUND(V5_AVG_KANS,6),
V7_AANTAL_KANS, V7_AVG_KANS, V8_AANTAL_KANS, ROUND(V8_AVG_KANS,6) V8_AVG_KANS ROUND(V7_AVG_KANS,6),
V9_AANTAL_KANS, ROUND(V9_AVG_KANS,6) V9_AVG_KANS
Of
(
Select WORP_XW, D, KAN,
case VERSIE_VX when "V5" then 5 when "V6" when then 6 "V7" when then 7 "V8" when then 8 "V9" then 9 end as VERSIE_VX
of VMENS. TOEVAL_BASIS_W' | TELLER_1 | »
)
pivot)
AVG (KAN) as AVG_KANS,
COUNT (KAN) AS AANTAL_KANS
by VERSIE_VX (V5, V6, V7, V8, V9 9 8 7 6 5)
)
ORDER BY D
)';
L_rc_a OPEN FOR ctt1;
LOOP
EXTRACTION l_rc_a IN aa;
EXIT WHEN l_rc_a % NOTFOUND;
-dbms_output.put_line (aa);
UTL_FILE.put_line (OutFile, aa, TRUE);
END LOOP;
END LOOP;
UTL_FILE.fclose (outfile);
END;
Error report:
ORA-29283: Ongeldige bestandsbewerking/ORA-29283: invalid file operation
ORA-06512: in 'SYS. UTL_FILE", regel 536
ORA-29283: Ongeldige bestandsbewerking/ORA-29283: invalid file operation
ORA-06512: in rule 14
29283 00000 - "invalid file operation.
* Cause: An attempt was made to read from a file or a directory which is
not exist, or the file or directory access was denied by the
Operating system.
* Action: Check access privileges to the file and directory on the file system
and if reading, check that the file exists.
The same is true when I use another script writes the results of a query to an external file. Y at - there someone who can tell me why I have an error message after running 8 ' e of this script.
With respect,
Michiel van MensThe second time through the outer loop, it will fail because you try to open a file that is already open. Move your utl_file.fclose statement of before the last "END LOOP '.
-
Unwanted using utl_file.put_line output result
I don't know how the white space between the PRTA_NEW_IDN_REC. PRTA_TO_IDN and. PRTA_TRANS_ID_REC QUANTITY. Thank you for your help in advance.
UTL_FILE. Put_line (f_ID_MAINT, RPAD (NVL(PRTA_TRANS_ID_REC. COMPTE,' '), 5,' ') |)
RPAD (NVL(PRTA_NEW_IDN_REC. PRTA_TO_IDN,' '), 6,' ') |
TO_CHAR (PRTA_TRANS_ID_REC. QUANTITY, ' 099999')
);
output
A0012112010 000002
A0014112010 000001
A0023112010 000002
A0025112010 000001
A0030112010 000001
Expected result:
A0101112010000002
D1055322779000005
D1055322503000008
D1055322547000009question isn't put_line, it has to do with your mask to_char.
If you do nothing, you will get a space for positive numbers and a '-' for negative.
You must add 'fm' in front of the initial '0', and the space is removed.
You can find the masks of format in SQL language reference manual.
http://download.Oracle.com/docs/CD/E11882_01/server.112/e17118/sql_elements004.htm#SQLRF00216--------
Sybrand Bakker
Senior Oracle DBA -
Hello world...
I use utl_file to write data defined in text files. In the utl_file.fopen I changed the default l 'size of the line max' 32767 when I got an error about the size of the line. After changing max line size paramaterer, I get a lot of space after each line.
This line size parameter max means that each line 'should' be of this size? why I get a lot of space after each line?
question 1:
======
How to remove the empty spaces I had after every line of my text file?
And I'm trying to find the length of the string that I utl_file.put_lineFILEHANDLE := UTL_FILE.FOPEN('TEST_UTL_FILE','file_name.txt', 'W',32767);
I'm trying to insert this length to a 'test' table, so that I can check the maximum length of each line that passes to the utl_file.
I have this command insert in my PL/SQL block
question 2:insert into test_number_char (num) values (dbms_lob.getlength(EXTRACTED_STRING)); and the data type of "num" column is number(20,0) I am getting the following error . ERROR getting members -1461 ORA-01461: can bind a LONG value only for insert into a LONG column
=======
How to get the length of the string that I write in the file?
Thank you
PhaniHey Brad,
>
question 1:
======
How to remove the empty spaces I had after every line of my text file?
>
something like that,string := Rtrim(string,' ');
question 2:
=======
How to get the length of the string that I write in the file?
>
Look at this,SQL> Set Serveroutput on SQL> Create or Replace Directory SOME_DIR As 'C:\Temp'; Directory created SQL> Create table Test_ As (Select dbms_random.string('X',10) as Txt From dual Connect by Level <= 2500); Table created SQL> SQL> Declare 2 v_column Varchar2(30); 3 l_utl_dir Varchar2(30) := 'SOME_DIR'; 4 l_utl_file Varchar2(30) := 'Some_File.txt'; 5 l_header Varchar2(32767) := Null; 6 l_utl_id UTL_FILE.FILE_TYPE; 7 Begin 8 DBMS_OUTPUT.ENABLE(32767); 9 10 l_utl_id := UTL_FILE.FOPEN( location => l_utl_dir 11 , filename => l_utl_file 12 , open_mode => 'w' 13 , max_linesize => 32767); 14 15 For i IN (SELECT Rowid 16 FROM TEST_) Loop 17 18 For x IN (SELECT COLUMN_NAME 19 , TABLE_NAME 20 FROM ALL_TAB_COLS 21 WHERE TABLE_NAME = 'TEST_') Loop 22 23 Execute Immediate 'select ' || x.column_name || ' from ' || 24 x.table_name || ' where rowid = :pi_input' 25 INTO v_column 26 Using IN i.Rowid; 27 28 l_header := l_header || v_column || ' '; 29 30 End Loop; 31 End Loop; 32 33 UTL_FILE.PUT_LINE( file => l_utl_id 34 , buffer => l_header ); 35 36 UTL_FILE.FCLOSE(file => l_utl_id); 37 38 DBMS_OUTPUT.PUT_LINE( LENGTH( l_header ) ); 39 End; 40 / 27500 PL/SQL procedure successfully completed
Hope this helps,
Christian Balz -
Procedure using utl_file.fopen
Hello
I want to open a file, read line by line, and if I find a particular word, I want to display the whole line.
I tried to write a procedure, but not getting desired do not output.
DECLARE
x utl_file.file_type;
y varchar2 (200);
BEGIN
x: = utl_file.fopen('TRACE1',DB_ora_111_trc.txt','R');
LOOP
BEGIN
UTL_FILE. GET_LINE(x,y);
If x = "select".
dbms_output.put_line (x);
end if;
EXCEPTION
WHEN NO_DATA_FOUND THEN EXIT;
END;
END LOOP;
UTL_FILE.fclose (x);
END;
/
Here I am opening a file of tkprof and trying to grep for select word and if he is found, select all to display query. The above doesn't show any output. Kindly help me as I'm new to coding.
Thank youuser10698496 wrote:
Thank you BlueShadow.I tried to run, but received the error as
ORA-06502: PL/SQL: digital or value error: character of number conversion error.I put the '+ 5' after barcket.
Oops, my bad. Sorry about that.
DECLARE f utl_file.file_type; s varchar2(2000); in_select boolean; BEGIN f := utl_file.fopen('TRACE1','DB_ora_1118250.trc.txt','R'); in_select := false; LOOP BEGIN UTL_FILE.GET_LINE(f,s); if lower(s) like '%select%' or in_select then dbms_output.put_line(s); if lower(s) like '%from%' then dbms_output.put_line('TABLES: '||substr(s,instr(s,'from')+5)); -- +5 to get past the from and the space character after it. end if; in_select := not(s like '%;'); -- stop when we get to ";" at end of a line. end if; EXCEPTION WHEN NO_DATA_FOUND THEN EXIT ; END; END LOOP; utl_file.fclose(f); END; / SELECT lpad(to_char(NVL(MAX(to_number(serial_num)), 0) + 1), 12, '0') FROM TABLES: SALES WHERE s_id = :1 AND s_name = :2 SELECT S_CODE FROM TABLES: S_MAST WHERE s_id = :1 AND s_name = :2
If you notice after 'from' the word TABLE is attached due to dbms_output.put_line('TABLES.)
But he did not cut the name of the table only and shown as output.Well, obviously, now we can see the entire SQL statement that you are querying, your table names are not on the same line as your statement 'FROM '.
This means that it won't be easy to spot where the tables are in the statement.Perhaps if you explained what you're actually trying to reach, then we can help you, but looks like you are trying to do something beyond the reach of reason.
I also tried to put the output in a file
DECLARE f utl_file.file_type; s varchar2(2000); in_select boolean; opfile utl_file.file_type; BEGIN f := utl_file.fopen('TRACE_EXTRACT','nis_trc.txt','R'); opfile := utl_file.fopen ('TRACE1',,'SELECT.txt','W'); in_select := false; LOOP BEGIN UTL_FILE.GET_LINE(f,s); if lower(s) like '%select%' or in_select then dbms_output.put_line(s); utl_file.put_line(opfile,s); in_select := not(s like '%;'); -- stop when we get to ";" at end of a line. end if; EXCEPTION WHEN NO_DATA_FOUND THEN EXIT ; END; END LOOP; utl_file.fclose(f); END; / ERROR at line 1: ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536 ORA-29283: invalid file operation ORA-06512: at line 8
The TRACE1 directory exist and I also granted READ/WRITE permissions. Why does this error happen?
Perhaps because of this...
opfile := utl_file.fopen ('TRACE1',,'SELECT.txt','W');
You seem to have an extra ',' in your settings.
-
How to get sql % number of dynamic sql code lines
Hello
In this procedure I'm inserting and updating using dynamic sql. Now I want to go back two more PARAMETERS, the parameter should be back the number of lines inserted and how updated by stmtas of UPDATE as well as an INSERT. I'm not able to do can help you on that?
CREATE OR REPLACE PROCEDURE Sp_Array_Test( PV_TGT_NAME IN VARCHAR2, PV_SRC_NAME IN VARCHAR2, PV_PK_COLS IN VARCHAR2, PN_ERR_CD OUT NUMBER, PN_ERR_MSG OUT VARCHAR2) AS TYPE ARR_TAB IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER; --UTL_FP UTL_FILE.FILE_TYPE; LV_AN_ BLOCK VARCHAR2(32767); LN_CUR BINARY_INTEGER := DBMS_SQL.OPEN_CURSOR; LN_DESC DBMS_SQL.DESC_TAB; LN_COL_CNT PLS_INTEGER := 0; LV_SEL_UPD_STMT VARCHAR2(4000); LV_SEL_INS_STMT VARCHAR2(4000); ARR_INDX NUMBER := 1; LV_DATA_TYPE VARCHAR2(8); LN_FIND_FLAG NUMBER := 0; LN_TAB ARR_TAB; LV_COLS_ARR ARR_TAB; LV_ERR_MSG VARCHAR2(500); --PROCEDURE FILE_WRITE ( FH_IN IN UTL_FILE.FILE_TYPE, -- STRING_IN IN VARCHAR2 ) IS --BEGIN -- UTL_FILE.PUT_LINE(FH_IN,STRING_IN); -- LV_AN_BLOCK := LV_AN_BLOCK||STRING_IN; --EXCEPTION -- WHEN OTHERS THEN -- RAISE; --END FILE_WRITE; BEGIN -- UTL_FP := UTL_FILE.FOPEN('TEST_DIR', 'TEST.sql', 'W'); LV_SEL_UPD_STMT := 'SELECT A.'||REPLACE(PV_PK_COLS,',','||A.')||' PK_COLS , A.* , B.ROWID FROM '||PV_SRC_NAME||' A, '||PV_TGT_NAME||' B WHERE '; LV_SEL_INS_STMT := 'SELECT A.* FROM '||PV_SRC_NAME||' A WHERE NOT EXISTS (SELECT ''1'' FROM '||PV_TGT_NAME||' B WHERE '; LN_TAB(ARR_INDX) := 'DECLARE '; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := 'CURSOR CUR_VIEW_UPD IS '||LV_SEL_UPD_STMT ; ARR_INDX := ARR_INDX + 1; SELECT SUBSTR(COLS,DECODE(RN,1,1,INSTR(COLS,',',1,RN-1)+1),DECODE(RN,1,INSTR(COLS,',',1,RN)-1,INSTR(COLS,',',1,RN)-INSTR(COLS,',',1,RN-1)-1)) BULK COLLECT INTO LV_COLS_ARR FROM ( SELECT RN, PV_PK_COLS||',' COLS FROM (SELECT ROWNUM RN FROM ALL_OBJECTS WHERE ROWNUM <= LENGTH(PV_PK_COLS)- LENGTH(REPLACE(PV_PK_COLS,','))+1)) ; FOR K IN 1 .. LV_COLS_ARR.COUNT LOOP LV_SEL_UPD_STMT := LV_SEL_UPD_STMT||' A.'||LV_COLS_ARR(K)||' = '; LN_TAB(ARR_INDX) := ' A.'||LV_COLS_ARR(K)||' = '; LV_SEL_UPD_STMT := LV_SEL_UPD_STMT||' B.'||LV_COLS_ARR(K) ||CASE WHEN K = LV_COLS_ARR.COUNT THEN NULL ELSE ' AND ' END; LN_TAB(ARR_INDX) := LN_TAB(ARR_INDX)||' B.'||LV_COLS_ARR(K) ||CASE WHEN K = LV_COLS_ARR.COUNT THEN ' ;' ELSE ' AND ' END; ARR_INDX := ARR_INDX + 1; END LOOP; LN_TAB(ARR_INDX) := 'CURSOR CUR_VIEW_INS IS '||LV_SEL_INS_STMT ; ARR_INDX := ARR_INDX + 1; FOR K IN 1 .. LV_COLS_ARR.COUNT LOOP LV_SEL_INS_STMT := LV_SEL_INS_STMT||' A.'||LV_COLS_ARR(K)||' = '; LN_TAB(ARR_INDX) := ' A.'||LV_COLS_ARR(K)||' = '; LV_SEL_INS_STMT := LV_SEL_INS_STMT||' B.'||LV_COLS_ARR(K) ||CASE WHEN K = LV_COLS_ARR.COUNT THEN NULL ELSE ' AND ' END; LN_TAB(ARR_INDX) := LN_TAB(ARR_INDX)||' B.'||LV_COLS_ARR(K) ||CASE WHEN K = LV_COLS_ARR.COUNT THEN ' );' ELSE ' AND ' END; ARR_INDX := ARR_INDX + 1; END LOOP; LV_ERR_MSG := 'WHILE PARSING SELECT STATEMENT -- '||LV_SEL_UPD_STMT; DBMS_SQL.PARSE(LN_CUR, LV_SEL_UPD_STMT, DBMS_SQL.NATIVE); LV_ERR_MSG := 'WHILE DESCRIBING SELECT STATEMENT -- '||LV_SEL_UPD_STMT; DBMS_SQL.DESCRIBE_COLUMNS(LN_CUR, LN_COL_CNT, LN_DESC); FOR i IN LN_DESC.FIRST .. LN_DESC.LAST LOOP IF LN_DESC(i).col_type = 2 THEN LV_DATA_TYPE := 'NUMBER'; ELSIF LN_DESC(i).col_type = 12 THEN LV_DATA_TYPE := 'DATE'; ELSE LV_DATA_TYPE := 'VARCHAR2'; END IF; LN_TAB(ARR_INDX) := ' T_'||LN_DESC(i).col_name||' DBMS_SQL.'||LV_DATA_TYPE||'_TABLE;'; ARR_INDX := ARR_INDX + 1; END LOOP; LN_TAB(ARR_INDX) := 'BEGIN '; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' EXECUTE IMMEDIATE ''ALTER SESSION SET NLS_DATE_FORMAT = ''''DD-MON-YYYY HH24:MI:SS'''''';'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' OPEN CUR_VIEW_UPD;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' LOOP'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' FETCH CUR_VIEW_UPD BULK COLLECT INTO T_'||LN_DESC(LN_DESC.FIRST).col_name||','; ARR_INDX := ARR_INDX + 1; FOR i IN LN_DESC.FIRST + 1 .. LN_DESC.LAST - 1 LOOP LN_TAB(ARR_INDX) := ' T_'||LN_DESC(i).col_name||','; ARR_INDX := ARR_INDX + 1; END LOOP; LN_TAB(ARR_INDX) := ' T_'||LN_DESC(LN_DESC.LAST).col_name||' LIMIT 500 ;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' FORALL I IN 1 .. '||'T_'||LN_DESC(LN_DESC.LAST).col_name||'.COUNT '; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' UPDATE '||PV_TGT_NAME||' SET '; ARR_INDX := ARR_INDX + 1; LN_FIND_FLAG := 0; FOR I IN LN_DESC.FIRST + 1 .. LN_DESC.LAST-1 LOOP FOR K IN 1 .. LV_COLS_ARR.COUNT LOOP LN_FIND_FLAG := 0; IF LN_DESC(I).COL_NAME = LV_COLS_ARR(K) THEN LN_FIND_FLAG := 1; EXIT; END IF; END LOOP; IF LN_FIND_FLAG = 0 THEN LN_TAB(ARR_INDX) := ' '||LN_DESC(i).col_name||' = '||'T_'||LN_DESC(i).col_name||'(I)'||CASE WHEN I = LN_DESC.LAST-1 THEN ' WHERE ' ELSE ',' END; ARR_INDX := ARR_INDX + 1; END IF ; END LOOP; LN_TAB(ARR_INDX) := ' ROWID = '||'T_'||LN_DESC(LN_DESC.LAST).col_name||'(I) ;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' COMMIT;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' EXIT WHEN CUR_VIEW_UPD%NOTFOUND;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' END LOOP;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' CLOSE CUR_VIEW_UPD;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' COMMIT;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' OPEN CUR_VIEW_INS;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' LOOP'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' FETCH CUR_VIEW_INS BULK COLLECT INTO T_'||LN_DESC(LN_DESC.FIRST+1).col_name||','; ARR_INDX := ARR_INDX + 1; FOR i IN LN_DESC.FIRST + 2 .. LN_DESC.LAST - 2 LOOP LN_TAB(ARR_INDX) := ' T_'||LN_DESC(i).col_name||','; ARR_INDX := ARR_INDX + 1; END LOOP; LN_TAB(ARR_INDX) := ' T_'||LN_DESC(LN_DESC.LAST-1).col_name||' LIMIT 500 ;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' FORALL J IN 1 .. '||'T_'||LN_DESC(LN_DESC.FIRST + 1).col_name||'.COUNT '; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' INSERT INTO '||PV_TGT_NAME||' ('; ARR_INDX := ARR_INDX + 1; FOR i IN LN_DESC.FIRST + 1 .. LN_DESC.LAST - 1 LOOP LN_TAB(ARR_INDX) := ' '||LN_DESC(i).col_name||CASE WHEN I = LN_DESC.LAST - 1 THEN ' )' ELSE ',' END ; ARR_INDX := ARR_INDX + 1; END LOOP; FOR i IN LN_DESC.FIRST + 1 .. LN_DESC.LAST - 1 LOOP LN_TAB(ARR_INDX) := CASE WHEN I = LN_DESC.FIRST + 1 THEN 'VALUES (' ELSE NULL END ||' T_'||LN_DESC(i).col_name||'(J)'||CASE WHEN I = LN_DESC.LAST - 1 THEN ' ) ;' ELSE ',' END ; ARR_INDX := ARR_INDX + 1; END LOOP; LN_TAB(ARR_INDX) := ' COMMIT;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' EXIT WHEN CUR_VIEW_INS%NOTFOUND;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' END LOOP;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' CLOSE CUR_VIEW_INS;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := ' COMMIT;'; ARR_INDX := ARR_INDX + 1; LN_TAB(ARR_INDX) := 'END ;'; ARR_INDX := ARR_INDX + 1; FOR J IN 1 .. LN_TAB.COUNT LOOP -- DBMS_OUTPUT.PUT_LINE( LN_TAB(J)); -- FILE_WRITE(UTL_FP,LN_TAB(J)); LV_AN_BLOCK := LV_AN_BLOCK||LN_TAB(J); END LOOP; -- UTL_FILE.FCLOSE(UTL_FP); EXECUTE IMMEDIATE LV_AN_BLOCK; PN_ERR_CD := 0; PN_ERR_MSG := 'Successful Completion'; EXCEPTION WHEN OTHERS THEN PN_ERR_CD := SQLCODE; PN_ERR_MSG := LV_ERR_MSG||' -- '||SQLERRM ; END; /
Thank you all for your answers. I agree with you all. I have manged this time by adding variable bind, then run it immediately ON aid. I don't know how it's going to be training.
From now on my side no problem I don't thank you.
-
How to *. ZIP has *. CSV file in the Oracle Directory?
Hello! How are you doing guys?
I have a question;
How to Zip, a CSV file in the oracle directory?
I use this method, but a mistake;
Error; Invalid file operation, this line: utl_file.get_raw (v_arquivo_out, strbufferdd);
___The Script___
v_arquivo_out: = utl_file.fopen ('ORA_DIR',-/ oracle/files/ORA/ORADIR /)
"DOC. CSV', - file name
"WORLD BANK");
UTL_FILE.get_raw (v_arquivo_out, strbufferdd); <-this line a mistake.
strbufferdd: = UTL_COMPRESS.lz_compress (strbufferdd, 6);
V_SDIRECTORY: = TO_CHAR (SYSDATE, ' DD_MM_YYYY_HH24.MI.) SS') | "_RETORNA. ZIP';
psDsc_File: = v_sDirectory;
v_arquivo_out2: = utl_file.fopen ('ORA_DIR',-/ oracle/files/ORA/ORADIR /)
psDsc_File,
'W');
-as_zip.
Utl_File.Put_Raw (v_arquivo_out2, strbufferdd);
UTL_FILE.fclose (v_arquivo_out);
UTL_FILE.fclose (v_arquivo_out2);
___End SCRIPT___
Help me?
Thank you to all the world, I have the solution;
Please see the procedure;
CREATE OR REPLACE PROCEDURE 'PR_RELAT_CSV '.
(
peCod_Prog in DOCUMENT. Type of Cod_Prog %,
psDsc_File out varchar2
)
IS
-variaveis para land
v_arquivo_out utl_file.file_type;
v_separator varchar2 (1): = "";
v_sDirectory varchar2 (200);
src_file BFILE.
v_content BLOB;
v_blob_len INTEGER.
v_file UTL_FILE.file_type;
v_buffer RAW (32767).
v_amount directory: = 32767;
v_pos INTEGER: = 1;
BEGIN
-DADOS PREENCHIDOS. ABAIXO, CRIAR PREENCHER E O LAND CSV
V_SDIRECTORY: = TO_CHAR (SYSDATE, ' DD_MM_YYYY_HH24.MI.) SS') |
' _RETORNA. CSV';
psDsc_File: = v_sDirectory;
v_arquivo_out: = utl_file.fopen ('ORA_DIR',-/ oracle/files/oradir/ora /)
psDsc_File,
'W');
cabecalho - write
UTL_FILE.put_line (v_arquivo_out,
"Organize" | v_separator | ' OPTIONS / Options'.
v_separator | "AP" | v_separator | "CODE" |
v_separator | 'Description of the PN | v_separator |
"Station". v_separator | "Initial SN | v_separator |
"Final SN | v_separator | 'Note ' | v_separator |
'Pos ' | v_separator,
(FALSE);
-write linhas
/ * n : = 0 ; Contador * /.
for rec_ (SELECT DISTINCT a.*, d.DSC_ITEM, e.COD_PN_MAT
OF pcm_subestacao one
LEFT JOIN (select b.cod_prog,
c.num_arj,
c.cod_itens,
c.DSC_ITEM,
c.COD_SEST_CONJ
of pcm_desenho b
INNER JOIN TABLE (fu_pcm_Combinar_Subestacao ('SYSTEM', b.cod_prog, b.num_arj, 0, null, null, null,)) c
ON b.num_arj = c.num_arj
and b.cod_prog = peCod_Prog) d
ON a.cod_sest_conj = d.cod_sest_conj
INNER JOIN pcm_mat_geral e
ON e.cod_cemb_mat = a.cod_cemb_estc
WHERE a.cod_prog = peCod_Prog
loop of the order of a.num_arj, num_ns_i, num_ns_fn)
/ * n : = n + 1 ; Contador linhas * /.
UTL_FILE.put_line (v_arquivo_out,
Chr (34) | Chr (32) | rec_. NUM_ARJ | Chr (32) |
Chr (34) | v_separator | Chr (34) | Chr (32) |
rec_. DSC_ITEM | Chr (32) | Chr (34) | v_separator |
Chr (34) | Chr (32) | rec_. COD_PN_SEST | Chr (32) |
Chr (34) | v_separator | Chr (34) | Chr (32) |
rec_. COD_CEMB_SEST | Chr (32) | Chr (34) |
v_separator | Chr (34) | Chr (32) | rec_. DSC_PN_SEST |
Chr (32) | Chr (34) | v_separator | Chr (34) |
Chr (32) | rec_. COD_PN_MAT | Chr (32) | Chr (34) |
v_separator | Chr (34) | Chr (32) | rec_. NUM_NS_I |
Chr (32) | Chr (34) | v_separator | Chr (34) |
Chr (32) | rec_. NUM_NS_FN | Chr (32) | Chr (34) |
v_separator | Chr (34) | Chr (32) | rec_. DSC_OBS |
Chr (32) | Chr (34) | v_separator | Chr (34) |
Chr (32) | rec_. IND_POS | Chr (32) | Chr (34) |
v_separator,
(FALSE);
end loop;
UTL_FILE.fclose (v_arquivo_out);
src_file: = BFILENAME ('ORA_DIR', psDsc_File);
DBMS_LOB. FileOpen (src_file, dbms_lob.file_readonly);
v_content: = utl_compress.lz_compress (src_file);
v_blob_len: = DBMS_LOB.getlength (v_content);
V_SDIRECTORY: = TO_CHAR (SYSDATE, ' DD_MM_YYYY_HH24.MI.) SS') |
' _RETORNA. CSV. ZIP';
psDsc_File: = v_sDirectory;
v_file: = utl_file.fopen ('ORA_DIR',-/ oracle/files/ORADIR/ORA /)
psDsc_File,
"WORLD BANK");
Everything v_pos< v_blob_len="">
DBMS_LOB. READ (v_content, v_amount, v_pos, v_buffer);
UTL_FILE.put_raw (v_file, v_buffer, TRUE);
v_pos: = v_pos + v_amount;
END LOOP;
UTL_FILE.fclose (v_file);
EXCEPTION
WHILE OTHERS THEN
IF UTL_FILE.is_open (v_file) THEN
UTL_FILE.fclose (v_file);
END IF;
LIFT;
END PR_RELAT_CSV;
-
How to split the file by using the utl package in oracle.
Hi all
I want ot create several files with utl_file.
Earlier, I'm writing itng cursor files together in a single file.
But now we must divide it into several files when the cursor recrds exceeded 10000.
So the file will become two if it crosses 10000 records Amend now
If a cursor has 30000 records then I hould create 3 files.
Here's how I wrote the simple logic to write the entire records from a single table.
UTL_FILE. PUTF (File1, head);
UTL_FILE.new_line (file1);
FOR vcur_torico_fetch IN cur_torico_fetch
LOOP
stmt: = "
|| Chr (9) | »
|| Chr (9) | vcur_torico_fetch. Application_classification
|| Chr (9) | »
|| Chr (9) | »
|| Chr (9) | vcur_torico_fetch. MY_COMP_CODE
|| Chr (9) | vcur_torico_fetch. OU_org_code;
UTL_FILE. PUTF (File1, stmt);
UTL_FILE.new_line (file1);
END LOOP;
UTL_FILE.fclose (file1);
Kindly let me know the logic to do this.
Best regards
Try this. I used object and I write 33333 lines. It will be writern in 4 files with lines of 10000, 10000, 10000 and 3333.
SQL> declare 2 l_file utl_file.file_type default NULL; 3 l_row_per_file integer default 10000; 4 l_file_name varchar2(100) default 'ALL_OBJECT_{FILENO}.CSV'; 5 l_file_dir varchar2(100) default 'KARDIR'; 6 l_file_no integer default 0; 7 begin 8 for i in ( 9 select object_id 10 , object_name 11 , ceil(rownum/l_row_per_file) file_no 12 from all_objects 13 where rownum <= 33333 14 ) 15 loop 16 if l_file_no != i.file_no 17 then 18 if utl_file.is_open(l_file) 19 then 20 utl_file.fclose(l_file); 21 end if; 22 23 l_file_no := i.file_no; 24 l_file := utl_file.fopen 25 ( 26 l_file_dir 27 , replace(l_file_name, '{FILENO}', to_char(l_file_no, 'fm099999')) 28 , 'w' 29 ); 30 end if; 31 32 utl_file.put_line(l_file, i.object_id || ',' || i.object_name); 33 end loop; 34 35 if utl_file.is_open(l_file) 36 then 37 utl_file.fclose(l_file); 38 end if; 39 end; 40 / PL/SQL procedure successfully completed. SQL>
In the unix box, check the file...
% ls - lrt ALL_OBJECT knani *. CSV | AWK '{print $9} ' | XARGS wc-l
10000 ALL_OBJECT_000001.CSV
10000 ALL_OBJECT_000002.CSV
10000 ALL_OBJECT_000003.CSV
3333 ALL_OBJECT_000004.CSV
33333 total
knani % -
How to generate a dynamic of variable
Hellomy version of oracle's
Oracle Database 11 g Enterprise Edition Release 11.2.0.3.0 - 64 bit Production
PL/SQL Release 11.2.0.3.0 - Production
"CORE 11.2.0.3.0 Production."
AMT for Linux: Version 11.2.0.3.0 - Production
NLSRTL Version 11.2.0.3.0 - Production
I use following code to create a file.
Declare
Type Typ_Test_Data is Table of TEST % Rowtype;
Test_Data Typ_Test_Data;
v_delimited varchar2 (1): =' | ' ;
L_Cur Sys_Refcursor;
L_Filehandle Utl_File.File_Type;
V_File_Path Varchar2 (1000): = 'abc ';
V_Table_Name Varchar2 (32): = 'TEST ';
P_Stg_Table_Owner varchar2 (32): = 'abc ';
v_partition_name varchar2 (32): = "P201308";
V_Str Varchar2 (20000);
V_Column_Names_Str Varchar2 (20000);
V_Column_Names_Str2 Varchar2 (32000);
V_Str1 Varchar2 (20000);
Startl_fileHandle: = Utl_File.Fopen (v_file_path, '05022015.txt', 'W');
IF UTL_FILE.IS_OPEN (l_fileHandle) = FALSE
THEN
Dbms_Output.put_line ('file is not open');
On the other
dbms_output.put_line ('File_is_open');
End If;
"/ * V_Str: = ' select * from '.
|| V_Table_Name
||' Partition (')
|| V_Partition_Name
||')'; */
"V_Str: = ' select * from '.
|| V_Table_Name;
Dbms_Output.put_line (v_column_names_str2);L_Cur open for V_Str;
loop
Extraction L_Cur bulk collect into test_data limit 1000;
Because me in 1.test_data. County
Loop
V_Str1: is Test_Data (I). Emp_Id | V_Delimited | Test_Data (I). Emp_name | V_Delimited | Test_Data (I). Address;
Dbms_Output.put_line (V_Str1);
-Utl_File.Put_Line (l_fileHandle, Test_Data (I). Emp_Id | V_Delimited | Test_Data (I). Emp_name | V_Delimited | Test_Data (I). Address);
Utl_File.put_line (l_fileHandle, V_Str1);
End loop;
When the test_data output. Count = 0;
End loop;
Close L_Cur;
Utl_File.Fclose_All ();end;
/This generates files. but I want below the dynamic type declaration. so that the same code can work for different tables. We do this for data archiving,
Type Typ_Test_Data is Table of TEST % Rowtype;
IS this possible? Yes, how?
Hello
You can find an example here
Re: export csv via pl/sql: select statement?
Concerning
Marcus
-
{ORA-06550: line 172, column 15:}
PLS-00103: encountered the symbol ". «» When expecting one of the following values:
;
ORA-06550: line 173, column 7:
PLS-00103: encountered the symbol "UTL_FILE.
ORA-06550: line 173, column 39:
PLS-00103: encountered the symbol ";" when expecting one of the following values:
. (, * % & -+ / at rem rest mod < an ID >)
< between double quote delimited identifiers of > < an exhibitor > (*) as
go to | {multiset in bulk}
{DECLARE
p_userid VARCHAR2: = 'CMSHPQ_USER ';
p_filename VARCHAR2: = 'XXXX ';
p_logfile VARCHAR2: = ' / apps/home/cmsftp/log/plsql.
CURSOR c_company (p_ivr_plan VARCHAR2)
IS
SELECT
t.ivr_plan_num,
t.ivr_plan_num,
t.compy_acronym,
t.compy_nme,
t.compy_nme,
t.ml_sec_num,
t.compy_symbl,
fn_get_fmv_rpt (SYSDATE, 'CMS' | t.compy_acronym |) (' _USER') JVM,.
T1.fa_num,
t.fa_name_hnw,
t.maint_in_progress_flag,
t.vc_branch_prefix,
T.usr_winlog_id,
t.blpt_pl_ef_dt,
t.compy_passwd,
NVL (c.cusip_num, t.compy_dwac_cusip_num) cusip_num
OF tb_fc_compy t, tb_fc_compy_ext t1, c corp
WHERE t.ivr_plan_num = t1.ivr_plan_num
AND t.compy_passwd = c.user_id (+)
AND o.user_id = TRIM (p_userid);
file_out_portrait UTL_FILE. TYPE_DE_FICHIER;
file_out_midas UTL_FILE. TYPE_DE_FICHIER;
v_portrait_str VARCHAR2 (32767).
v_midas_str VARCHAR2 (32767).
v_is_firstline BOOLEAN: = TRUE;
v_ivr_plan_num VARCHAR2 (30);
v_midas_filepath VARCHAR2 (100);
v_portrait_filepath VARCHAR2 (100);
v_midas_filename VARCHAR2 (100);
v_portrait_filename VARCHAR2 (100);
BEGIN
DBMS_OUTPUT. PUT_LINE ('SUCCESS1');
pk_xop_batch_feeds.pr_batch_feed_errors (p_logfile,
"Generating Company feed for the USER:' |" p_userid
);
DBMS_OUTPUT. PUT_LINE ('SUCCESS2');
SELECT MIDAS_FILE_PATH,
PORTRAIT_FILE_PATH,
MIDAS_FILE_NAME,
PORTRAIT_FILE_NAME
BY v_midas_filepath,
v_portrait_filepath,
v_midas_filename,
v_portrait_filename
OF tb_xop_batch_job_info
WHERE job_id = 5;
DBMS_OUTPUT. PUT_LINE ('SUCCESS3');
pk_xop_batch_feeds.pr_batch_feed_errors (p_logfile,
' midas_file_path:' | v_midas_filepath |
' portrait_file_path:' | v_portrait_filepath |
' midas_file_name:' | v_midas_filename |
' portrait_file_name:' | v_portrait_filename
);
file_out_portrait: =.
UTL_FILE. FOPEN (v_portrait_filepath, p_filename, 'W');
file_out_midas: =.
UTL_FILE. FOPEN (v_midas_filepath, p_filename, 'W');
DBMS_OUTPUT. PUT_LINE ('SUCCESS4');
SELECT ivr_plan_num
IN v_ivr_plan_num
OF tb_fc_compy
WHERE compy_passwd = p_userid;
FOR v_optionee IN c_company (v_ivr_plan_num)
LOOP
DBMS_OUTPUT. PUT_LINE ('SUCCESS5');
v_portrait_str: =.
("EXSOP"
||' /+/'
|| NULL VALUE
||' /+/'
|| t.ivr_plan_num
||' /+/'
|| t.ivr_plan_num
||' /+/'
||' CMS'
| t.compy_acronym
|' _USER'
||' /+/'
| t.compy_nme
||' /+/'
| t.compy_nme
||' /+/'
|| NULL VALUE
||' /+/'
|| t.ml_sec_num
||' /+/'
| t.compy_symbl
||' /+/'
|| fn_get_fmv_rpt (sysdate, 'CMS'
| t.compy_acronym
(| '_USER')
||' /+/'
|| T1.fa_num
||' /+/'
|| t.fa_name_hnw
||' /+/'
|| t.maint_in_progress_flag
||' /+/'
|| t.vc_branch_prefix
||' /+/'
|| NULL VALUE
||' /+/'
|| T.usr_winlog_id
);
UTL_FILE. Put_line (file_out_portrait, v_portrait_str);
-Check if Midas must be performed
IF fn_is_first_sat
THEN
-Search header
IF v_is_firstline
THEN
pk_xop_batch_feeds.pr_batch_feed_errors (p_logfile,
'Head of Midas '.
);
v_midas_str: =.
("Company Name"
|| Chr (9)
||' XOP user ID'
|| Chr (9)
||' Symbol '
|| Chr (9)
||' Security number of ML'
|| Chr (9)
||' CUSIP number '
|| Chr (9)
||' IVR Plan Num'
);
UTL_FILE. Put_line (file_out_midas, v_midas_str);
v_is_firstline: = FALSE;
END IF;
v_midas_str: =.
(v_midas_company.compy_nme: chr (9))
| v_midas_company.compy_passwd | Chr (9)
| v_midas_company.compy_symbl | Chr (9)
|| v_midas_company.ml_sec_num | Chr (9)
|| v_midas_company.cusip_num | Chr (9)
|| v_midas_company.ivr_plan_num);
UTL_FILE. Put_line (file_out_midas, v_midas_str);
END IF;
END OF LOOP
-pr_batch_feed_errors (p_logfile,
-Created in the company of power for the user.
-- || p_userid);
-classify Midas and Portrait
UTL_FILE. FCLOSE (file_out_portrait);
UTL_FILE. FCLOSE (file_out_midas);
EXCEPTION
WHILE OTHERS
THEN
pr_batch_feed_errors
(p_logfile,
"Critical error! Code '
|| SQLCODE
|| ':'
|| SQLERRM
|| "at".
|| USER
|| 'pk_xop_batch_feeds.pr_company '.
);
END;
/}
Hi friends, everyone can you help me clear the error I mentioned above. Thanks in advanceSee, how your formatted code look like...
DECLARE p_userid VARCHAR2 := 'CMSHPQ_USER'; p_filename VARCHAR2 :='XXXX'; p_logfile VARCHAR2 :='/apps/home/cmsftp/log/plsql'; CURSOR c_company (p_ivr_plan VARCHAR2) IS SELECT t.ivr_plan_num, t.ivr_plan_num, t.compy_acronym, t.compy_nme, t.compy_nme, t.ml_sec_num, t.compy_symbl, fn_get_fmv_rpt(SYSDATE,'CMS' ||t.compy_acronym ||'_USER') fmv, t1.fa_num, t.fa_name_hnw, t.maint_in_progress_flag, t.vc_branch_prefix, T.usr_winlog_id, t.blpt_pl_ef_dt , t.compy_passwd, NVL(c.cusip_num,t.compy_dwac_cusip_num) cusip_num FROM tb_fc_compy t, tb_fc_compy_ext t1, corp c WHERE t.ivr_plan_num = t1.ivr_plan_num AND t.compy_passwd = c.user_id(+) AND o.user_id = TRIM(p_userid); file_out_portrait UTL_FILE.FILE_TYPE; file_out_midas UTL_FILE.FILE_TYPE; v_portrait_str VARCHAR2 (32767); v_midas_str VARCHAR2 (32767); v_is_firstline BOOLEAN := TRUE; v_ivr_plan_num VARCHAR2 (30); v_midas_filepath VARCHAR2 (100); v_portrait_filepath VARCHAR2 (100); v_midas_filename VARCHAR2 (100); v_portrait_filename VARCHAR2 (100); BEGIN DBMS_OUTPUT.PUT_LINE('SUCCESS1'); pk_xop_batch_feeds.pr_batch_feed_errors (p_logfile, 'Generating Company feed for USER:' || p_userid ); DBMS_OUTPUT.PUT_LINE('SUCCESS2'); SELECT MIDAS_FILE_PATH, PORTRAIT_FILE_PATH, MIDAS_FILE_NAME, PORTRAIT_FILE_NAME INTO v_midas_filepath, v_portrait_filepath, v_midas_filename, v_portrait_filename FROM tb_xop_batch_job_info WHERE job_id = 5; DBMS_OUTPUT.PUT_LINE('SUCCESS3'); pk_xop_batch_feeds.pr_batch_feed_errors (p_logfile, 'midas_file_path:' || v_midas_filepath|| 'portrait_file_path:' || v_portrait_filepath|| 'midas_file_name:' || v_midas_filename|| 'portrait_file_name:' || v_portrait_filename ); file_out_portrait := UTL_FILE.FOPEN (v_portrait_filepath, p_filename, 'W'); file_out_midas := UTL_FILE.FOPEN (v_midas_filepath, p_filename, 'W'); DBMS_OUTPUT.PUT_LINE('SUCCESS4'); SELECT ivr_plan_num INTO v_ivr_plan_num FROM tb_fc_compy WHERE compy_passwd = p_userid; FOR v_optionee IN c_company(v_ivr_plan_num) LOOP DBMS_OUTPUT.PUT_LINE('SUCCESS5'); v_portrait_str := ('EXSOP' ||'/+/' ||NULL ||'/+/' ||t.ivr_plan_num ||'/+/' ||t.ivr_plan_num ||'/+/' ||'CMS' ||t.compy_acronym ||'_USER' ||'/+/' ||t.compy_nme ||'/+/' ||t.compy_nme ||'/+/' || NULL ||'/+/' || t.ml_sec_num ||'/+/' ||t.compy_symbl ||'/+/' ||fn_get_fmv_rpt(sysdate,'CMS' ||t.compy_acronym ||'_USER') ||'/+/' ||t1.fa_num ||'/+/' ||t.fa_name_hnw ||'/+/' ||t.maint_in_progress_flag ||'/+/' ||t.vc_branch_prefix ||'/+/' ||NULL ||'/+/' ||T.usr_winlog_id ); UTL_FILE.PUT_LINE (file_out_portrait, v_portrait_str); -- check if Midas need to be run IF fn_is_first_sat THEN --check for header IF v_is_firstline THEN pk_xop_batch_feeds.pr_batch_feed_errors (p_logfile, 'Midas Header' ); v_midas_str := ('Company Name' ||chr(9) ||'XOP User ID' ||chr(9) ||'Symbol' ||chr(9) ||'ML Security Number' ||chr(9) ||'CUSIP Number' ||chr(9) ||'IVR Plan Num' ); UTL_FILE.PUT_LINE (file_out_midas, v_midas_str); v_is_firstline := FALSE; END IF; v_midas_str := (v_midas_company.compy_nme||chr(9) ||v_midas_company.compy_passwd||chr(9) ||v_midas_company.compy_symbl||chr(9) ||v_midas_company.ml_sec_num||chr(9) ||v_midas_company.cusip_num||chr(9) ||v_midas_company.ivr_plan_num); UTL_FILE.PUT_LINE (file_out_midas, v_midas_str); end if; END LOOP;--"Semi colon added" -- pr_batch_feed_errors (p_logfile, -- 'Created company feed for User' -- || p_userid); -- close Midas and Portrait file UTL_FILE.FCLOSE (file_out_portrait); UTL_FILE.FCLOSE (file_out_midas); EXCEPTION WHEN OTHERS THEN pr_batch_feed_errors ( p_logfile, 'Critical Error! Code ' || SQLCODE || ':' || SQLERRM || ' at ' || USER || 'pk_xop_batch_feeds.pr_company' ); END;
-
How to extract .csv for each table
Hi all
I have a query:
Select distinct ' SELECT * FROM BILL_M.' | Table_name | ';' from all_tab_columns t
where t.owner = 'BILL_M. '
and table_name like '% DICT '.
The query returns 80 s table... How can I extract these 80 to 80 csvs table?
Any help is appreciated.
Kind regards.Just an example as a starting point...
As user sys:
CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles' / GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser /
As myuser:
CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2 ,p_dir IN VARCHAR2 ,p_header_file IN VARCHAR2 ,p_data_file IN VARCHAR2 := NULL) IS v_finaltxt VARCHAR2(4000); v_v_val VARCHAR2(4000); v_n_val NUMBER; v_d_val DATE; v_ret NUMBER; c NUMBER; d NUMBER; col_cnt INTEGER; f BOOLEAN; rec_tab DBMS_SQL.DESC_TAB; col_num NUMBER; v_fh UTL_FILE.FILE_TYPE; v_samefile BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file); BEGIN c := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE); d := DBMS_SQL.EXECUTE(c); DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab); FOR j in 1..col_cnt LOOP CASE rec_tab(j).col_type WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val); WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val); ELSE DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); END CASE; END LOOP; -- This part outputs the HEADER v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767); FOR j in 1..col_cnt LOOP v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),','); END LOOP; -- DBMS_OUTPUT.PUT_LINE(v_finaltxt); UTL_FILE.PUT_LINE(v_fh, v_finaltxt); IF NOT v_samefile THEN UTL_FILE.FCLOSE(v_fh); END IF; -- -- This part outputs the DATA IF NOT v_samefile THEN v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767); END IF; LOOP v_ret := DBMS_SQL.FETCH_ROWS(c); EXIT WHEN v_ret = 0; v_finaltxt := NULL; FOR j in 1..col_cnt LOOP CASE rec_tab(j).col_type WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val); v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',','); WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val); v_finaltxt := ltrim(v_finaltxt||','||v_n_val,','); WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val); v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),','); ELSE DBMS_SQL.COLUMN_VALUE(c,j,v_v_val); v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',','); END CASE; END LOOP; -- DBMS_OUTPUT.PUT_LINE(v_finaltxt); UTL_FILE.PUT_LINE(v_fh, v_finaltxt); END LOOP; UTL_FILE.FCLOSE(v_fh); DBMS_SQL.CLOSE_CURSOR(c); END;
This allows the header line and the data to write into files separate if necessary.
for example
SQL> exec run_query('select * from emp','TEST_DIR','output.txt'); PL/SQL procedure successfully completed.
Output.txt file contains:
empno,ename,job,mgr,hiredate,sal,comm,deptno 7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20 7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30 7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30 7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20 7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30 7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30 7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10 7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20 7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10 7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30 7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20 7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30 7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20 7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10
The procedure allows for the header and the data to separate files if necessary. Just by specifying the file name "header" will put the header and the data in a single file.
Adapt to the exit of styles and different types of data are needed.
You can then call this procedure for all the tables that you want to extract, with names appropriate for each.
-
UTL_FILE text file writing
Dear all,
I use the UTL_FILE to write a text file.
sample:C:=sample.txt; F := UTL_FILE.FOPEN('EX',C,'W'); for I in C1 LOOP UTL_FILE.PUT_LINE(F, I.1||'|'|| I.2||'|'|| I.3||'|'|| I.4||'|'|| I.5); UTL_FILE.FFLUSH(F); end LOOP; utl_file.fclose(f); end; {CODE} When i open the txt file in Notepad , The data coming in the single line with some enter key ( Carriage val)
1233 | 1111 | 1111 | 1111 (square box) 1222 | 1111 | 1111 | 1111 (square box) 1211 | 1111 | 1111 | 1111
How to remove the key enter during the writing of the text file. Or any other solution to get a notebook for the sub file condition
Thanks in advance.Result needed. 1233|1111|1111|1111 1222|1111|1111|1111 1211|1111|1111|1111
See you soon,.
San.Your database server is likely to be Unix or Linux, right? Which means that it uses a single character (LF) to "new line", rather than Windows that use two characters (CR - LF) to 'new line '.
(If you open your file with WordPad instead of NotePad it will probably look OK.)UTL_FILE. Put_line uses as a "new line" everything that uses the o/s database server.
So if you want to write a file to be used specifically in Windows, you can make your own "new line" rather than using the servers.
Use PUT rather than PUT_LINE and simply add the two characters that Windows uses to "new line":UTL_FILE.PUT(F, I.1||'|'|| I.2||'|'|| I.3||'|'|| I.4||'|'|| I.5|| CHR(13) || CHR(10) );
Maybe you are looking for
-
constant of flickering in itunes stroe
Hello Once I go to the iTunes store that my screen flickers constantly, how it be repaired?
-
Urgent: remove a known pattern of an array of Boolean
Hi, I have a Boolean data chunk and I would like to browse the model following '111000' all the data and remove this pattern repeated data. I would be very happy if you could show me how do it in LabVIEW. An example of code would be great. Also is th
-
My HP Officejet 6500 has more makes noises at the start
I've owned this printer this 6500 more printer for over 2 years now. He made a few noises when starting. Although there are no noise during printing or scanning. Should I be worried. It is the cleaning of printheads. The printer loses ink in the proc
-
Why my cd s divided from the center of the thenthey are not playable?
CDS split since the middle of the ward, and then they don't work it's been on 5 CD diff now so I think go a diff consloe
-
PE T620 (Rackmount) vs Dell MD1000
Hello a support or perhaps only recommended PowerEdge to connect a Md1000 to a Dell PE T620 (Rackmount)? Maybe: LSI MegaRAID SAS 928 x series with 2 SFF-8088 external connectors for neighter H800 Dell or Dell H810 Controller is listed as compatible w