Search in txt file using PL/SQL
Is there any way to search for a string in a text file using a PL/SQL block??
Thnks in advance.
Ashish
Richard:
It would depend on the nature of the text file, but it could be done for most plain text files. If there is some consistent delimiter, that is, the text file is fielded in some way, you could define an external table with the appropriate structure then use normal SQL queries against the particular fields from the file.
If the file is just plain text with no fields, you could create an external table something like:
CREATE TABLE myexternal (
line VARCHAR2(4000),
ORGANIZATION EXTERNAL
(TYPE oracle_loader
DEFAULT DIRECTORY mydirectory
ACCESS PARAMETERS
(RECORDS DELIMITED BY newline
BADFILE 'textfile.bad'
DISCARDFILE 'textfile.dis'
LOGFILE 'textfile.log'
(line CHAR(4000) NULLIF line = blanks))
LOCATION ('textfile.txt'))
REJECT LIMIT UNLIMITEDThen use normal sql to search the contents of that file.
I have not done any benchmarks on this, but my gut feel is that it would be significantly faster than using utl_file to loop over the lines looking for specific content.
In one of our warehouse load programs, we process a text file that is typically about 7Mb in under 30 seconds.
John
Similar Messages
-
How do i search for a string in a txt file using java??
How do i search for a string in a txt file using java??
could you please help thanks
JRegular expressinos work just fine, especially when
searching for patterns. But they seem to be impying
it's a specific group of characters they're looking
for, and indexOf() is much faster than a regex.If he's reading from a file, the I/O time will likely swamp any performance hit that regex introduces. I think contains() (or indexOf() if he's not on 5.0 yet) is preferable to regex just because it's simpler. (And in the case of contains(), the name makes for a very clear, direct mapping between your intent and the code that realizes it.) -
Loading the data from a packed decimal format file using a sql*loader.
Hi ,
In one of the project i'm working here i have to load the data into oracle table from a file using a Sql*loader but the problem is the data file is in the packed decimal format so please let me know if there is any way to do this....I search a lot regarding this ..If anybody faced such type of problem ,then let me the steps to solve this.
Thanks in advance ,
Narasingarao.declare
f utl_file.file_type;
s1 varchar2(200);
s2 varchar2(200);
s3 varchar2(200);
c number := 0;
begin
f := utl_file.fopen('TRY','sample1.txt','R');
utl_file.get_line(f,s1);
utl_file.get_line(f,s2);
utl_file.get_line(f,s3);
insert into sampletable (a,b,c) values (s1,s2,s3);
c := c + 1;
utl_file.fclose(f);
exception
when NO_DATA_FOUND then
if utl_file.is_open(f) then utl_file.fclose(f); ens if;
dbms_output.put_line('No. of rows inserted : ' || c);
end;SY. -
Writing into Excel file using PL/SQL and formatting the excel file
Hi,
I am writing into a excel file using PL/SQL and I want to make the first line bold on the excel. Also let me know if there are any other formatting options when writing into excel.
Regards,
-AnandI am writing into a excel file using PL/SQL
Re: CSV into Oracle and Oracle into CSV
check that thread or search in this forum... -
Display data in log file using PL/SQL procedure
Just as srw.message is used in Oracle RDF Reports to display data in log file in Oracle Apps, similarly how it is possible to display data in log file using PL/SQL procedure?
Please also mention the syntax too.Pl post details of OS, database and EBS versions.
You will need to invoke the seeded FND_LOG procedure - see previous discussions on this topic
Enable debug for pl/sql
https://forums.oracle.com/forums/search.jspa?threadID=&q=FND_LOG&objID=c3&dateRange=all&userID=&numResults=15&rankBy=10001
HTH
Srini -
Read a Document and replace the text numbers in a txt file using c++..
For ex:
Before Document:
hai hello my daily salary is two thousand and five and your salary is five billion. my age is
twenty-five.
After Document:
hai hello my daily salary is # and your salary is #. my age is #.
All the text numbers and i put the # symbol..
I am trying this code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream myfile_in ("input.txt");
ofstream myfile_out ("output.txt");
string line;
void find_and_replace( string &source, string find, string replace ) {
size_t j;
for ( ; (j = source.find( find )) != string::npos ; ) {
source.replace( j, find.length(), replace );
myfile_out << source <<endl;
cout << source << endl;
int main () {
if (myfile_in.is_open())
int i = 0,j;
//string strcomma ;
// string strspace ;
while (! myfile_in.eof() )
getline (myfile_in,line);
string strcomma= "two";
string strspace = "#";
find_and_replace( line , strcomma , strspace );
i++;
myfile_in.close();
else cout << "Unable to open file(s) ";
system("PAUSE");
return 0;
Please help me.. Give me the correct code..Open the file as a RandomAccessFile. Check its length. Declare a byte array as big as its length and do a single read to get the file into RAM.
Is this a simple text file (bytes)? No problem. If it's really 16-bit chars, use java.nio to first wrap the byte array as a ByteBuffer and then view the ByteBuffer as a CharBuffer.
Then you're ready for search/replace. Do it as you would in any other language. Be sure to use System.arraycopy() to shove your bytes right (replace bigger than search) or left (replace smaller than search).
When done, a single write() to the RandomAccessFile will put it all back. As you search/replace, keep track of size. If the final file is smaller than the original, use a setLength() to the new size to avoid extraneous data at the end. -
Creating a text file using pl/sql
how can one create a text file using pl/sql?
Say for example abcd.txt in the d: drive
(d:\abcd.txt)
on a windows nt server<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by bhrigu nagal ([email protected]):
thanks for your replies
I had already set the utl_file_dir parameter
I tried the utl package and wrote the following code but got some errors
declare
filehandler UTL_FILE.FILE_TYPE;
begin
filehandler:=UTL_FILE.fopen('d:/intel/','myfile.txt','w');
utl_file.put_line(filehandler,'look masjdfgsd\n');
utl_file.fclose(filehandler);
exception when utl_file.invalid_path then
raise_application_error(-20023,'bhrigu ,chk the path');
end;
the errors
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at "SYS.UTL_FILE", line 101
ORA-06512: at "SYS.UTL_FILE", line 157
ORA-06512: at line 4
if u know what this is please tell me
thanks bhrigu
<HR></BLOCKQUOTE>
U need :
1) To have UTL_FILE_DIR param in the init file of the instance with the same directory (don't forget to stop and restart the base)
2) Handled the exceptions listed in the utl_file package (Oracle_home\rdbms\admin\utlfile.sql) in your source.
3) Turn set serveroutput on in SQL*Plus.
Run your procedure and see the error message to debug.
Good luck
null -
How can I create an csv/excel file using pl/sql and then sending that file
How can I create an csv/excel file using pl/sql and then sending that file to a clients site using pl/sql?
I know how to create the csv/excel file but I can't figure out how I would get it to the clients site.968776 wrote:
How can I create an csv/excel file using pl/sql and then sending that file to a clients site using pl/sql?
I know how to create the csv/excel file but I can't figure out how I would get it to the clients site.You are trying to do it at a wrong place..
Whay do you want database (pl/sql) code to do these things?
Anyhow, you may be interested in :
{message:id=9360007}
{message:id=9984244} -
How to retrieve IndividualStrings from a txt file using String Tokenizer.
hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
the data in my txt file looks like this way.
Data1;
abc; cder; efu; frg;
abc1; cder2; efu3; frg4;
Data2
sdfabc; sdfcder; hvhefu; fgfrg;
uhfhabc; gffjcder; yugefu; hhfufrg;
Data3
val1; val2; val3; val4; val5; val6;
val1; val2; val3; val4; val5; val6;
val1; val2; val3; val4; val5; val6;
val1; val2; val3; val4; val5; val6;
i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
Regards,Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
I would suggest something like this general framework:
//make a BufferedReader up here...
do
String line = myBufferedReader.readLine();
if (line!=null && line.trim().length()>0)
line = line.trim();
//do some processing on the line
while (line!=null);So what processing to do inside the if statement?
Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
strtok = new StringTokenizer(line, ";, ");
if (sectionNo==0)
//read the tokens into the Labels1 collection
else if (sectionNo==1)
//read the tokens into the Labels2 collection
else //sectionNo must be 2
//create a new line in your table model and populate it with the token values...
}I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
Good luck. -
Downloading BLOB to a file using pl/sql toolkit
Created an Oracle Reports RDF file using the reports builder (9.0.2.x).
Uploaded the file into the database in a BLOB column using the following code:
>>>>
SET VERIFY OFF
DECLARE
p_bfile BFILE ;
p_blob BLOB ;
BEGIN
p_bfile := BFILENAME('CDR_REPORTS', '&1') ;
INSERT INTO RPTIDE (RPTID, RPTMODULE) VALUES ('&1', EMPTY_BLOB()) RETURNING
RPTMODULE INTO p_blob ;
DBMS_LOB.FILEOPEN(p_bfile, DBMS_LOB.FILE_READONLY);
DBMS_LOB.LOADFROMFILE(p_blob, p_bfile, DBMS_LOB.GETLENGTH(p_bfile));
DBMS_LOB.FILECLOSE(p_bfile);
COMMIT ;
END ;
<<<<<
Now when we try to download the same file using pl/sql web toolkit (code pasted
below), the file downloads fine (with exact same file size as before), but no
longer can open the file in Reports Builder anymore. Get "Cannot open file"
error in reports builder. Is it getting corrupt or am I doing something wrong?
>>>>
CREATE OR REPLACE PROCEDURE filedownload(p_rpt IN VARCHAR2) AS
p_file blob;
p_mime_type varchar2(50);
p_offset integer := 1;
p_len number;
p_buf RAW(32000);
p_buf_size integer:= 32000;
BEGIN
SELECT rptmodule, 'application/x-zip'
INTO p_file, p_mime_type
FROM rptide
WHERE rptid = p_rpt ;
OWA_UTIL.MIME_HEADER(p_mime_type);
p_len := DBMS_LOB.GETLENGTH(p_file);
WHILE p_offset < p_len LOOP
DBMS_LOB.READ(p_file, p_buf_size, p_offset, p_buf);
HTP.PRN(UTL_RAW.CAST_TO_VARCHAR2(p_buf));
p_offset := p_offset + p_buf_size;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN HTP.PRN('No document specified') ;
WHEN OTHERS THEN HTP.P('filedownload: '||SQLERRM);
END filedownload ;
<<<<<The answer to this problem was to set the NLS_LANGUAGE for the DAD to an 8-bit character set since the database charset was 8-bit. It seems, by default, the web toolkit assumes a 7-bit character set.
-
Creating Files Using PL/SQL?
Hi,
Is there a way to create a file using PL/Sql? It seems that the
utl_file package doesn't allow you to create a file. It only
allows you to read, write to a file that already exists there.
Thanks
VicMake sure the following is set in the init.ora:
UTL_FILE_DIR = /path/to/your/file/directory (for unix)
or
UTL_FILE_DIR = <drive>:\path\to\your\file\directory (for windows) -
Read XML File Using PL/SQL
Hi,
I have to read a XML file using PL/SQL. I am new to this so please explain in easy steps.
Regards,
SFSTEP - 2
SQL>
SQL> DECLARE
2 l_ctx dbms_xmlsave.ctxType ;
3 l_xml CLOB :=
4 '<?xml version="1.0" encoding="UTF-8" ?>
5 <NewDataSet>
6 <ROW>
7 <DEPARTMENT>BA52</DEPARTMENT>
8 <PCS_CONTRACT_TAG>MD-3GSM</PCS_CONTRACT_TAG>
9 <LOCATION>Australia</LOCATION>
10 <MAY_2006>21668</MAY_2006>
11 </ROW>
12 <ROW>
13 <DEPARTMENT>BA501</DEPARTMENT>
14 <PCS_CONTRACT_TAG>MD-3GSM</PCS_CONTRACT_TAG>
15 <LOCATION>China</LOCATION>
16 <MAY_2006>8166</MAY_2006>
17 </ROW>
18 <ROW>
19 <DEPARTMENT>BA522</DEPARTMENT>
20 <PCS_CONTRACT_TAG>MD-3GSM</PCS_CONTRACT_TAG>
21 <LOCATION>Australia</LOCATION>
22 <MAY_2006>21668</MAY_2006>
23 </ROW>
24 </NewDataSet>' ;
25 BEGIN
26 l_ctx := dbms_xmlsave.newContext(targetTable => 'XML_INSERT');
27 dbms_output.put_line(dbms_xmlsave.insertXML(ctxHdl => l_ctx,
28 xDoc => l_xml) ||
29 ' rows inserted.');
30 dbms_xmlsave.closeContext(l_ctx);
31 END;
32 /
3 rows inserted.
PL/SQL procedure successfully completed.Regards.
Satyaki De. -
Generating text file using PL/SQL
can any body send sample program how to generate text file using PL/SQL program.I want to store table data into that text file.
Hi,
try this.
Thanks
CREATE OR REPLACE procedure write_index (TABLE_NAME_ACCEPT VARCHAR2) IS
id UTL_FILE.FILE_TYPE;
name VARCHAR2(20) := 'e:\db_coca\input';
err VARCHAR2(100);
ColNameLength Integer;
NumberoFColumns Integer;
num NUMBER;
i integer;
loc_query VARCHAR2(2000);
cursor_name INTEGER;
ret INTEGER;
l_const_name VARCHAR2(30);
CURSOR c_columns(i_Constraint_name VARCHAR2) IS
SELECT *
FROM all_cons_columns
WHERE CONSTRAINT_NAME = i_Constraint_name
order by table_name;
BEGIN
DBMS_OUTPUT.PUT_LINE('BEFORe OPEN');
--id := UTL_FILE.FOPEN('e:\db_coca\input',name,'w');
--IF UTL_FILE.IS_OPEN(id) THEN
-- DBMS_OUTPUT.PUT_LINE('Opened');
--ELSE
-- DBMS_OUTPUT.PUT_LINE('Still Closed');
--END IF;
DBMS_OUTPUT.PUT_LINE('AFTER OPEN');
--The table generation script
loc_query := 'Select CONSTRAINT_NAME from user_constraints ';
loc_query := loc_query || ' where owner = ' || '''CPS''';
loc_query := loc_query || ' AND CONSTRAINT_TYPE = ' || '''P''';
dbms_output.put_line('TABLE_NAME_ACCEPT = ' || TABLE_NAME_ACCEPT);
IF NOT (TABLE_NAME_ACCEPT IS NULL ) THEN
loc_query := loc_query || ' AND TABLE_NAME like ''';
loc_query := loc_query || TABLE_NAME_ACCEPT ;
loc_query := loc_query || '''';
END IF;
cursor_name := DBMS_SQL.OPEN_CURSOR;
dbms_output.put_line('Query = ' || loc_query);
DBMS_SQL.PARSE(cursor_name, loc_query, DBMS_SQL.v7);
dbms_output.put_line('After parse');
dbms_sql.DEFINE_COLUMN(cursor_name, 1,l_const_name, 30);
ret := DBMS_SQL.EXECUTE(cursor_name);
-- IF ret > 0 THEN
LOOP
dbms_output.put_line('return = ' || ret);
IF DBMS_SQL.FETCH_ROWS(cursor_name) > 0 THEN
dbms_sql.COLUMN_VALUE(cursor_name, 1,l_const_name);
-- dbms_sql.BIND_VARIABLE(cursor_name,
l_const_name,CONSTRAINT_NAME);
-- FOR C10 in Table_Loop Loop --The cursor
for the table name
Select COunt(*) INTO NumberoFColumns from
all_cons_columns
Where CONSTRAINT_NAME = l_const_name;
-- FOR C11 IN c_columns(l_const_name) LOOP
-- End loop;
-- UTL_FILE.PUT(id, ');');
ELSE EXIT;
END if; --THe 1 st cursor if is closed
End Loop; --The table loop ends here
DBMS_SQL.CLOSE_CURSOR(cursor_name);
-- END IF;
-- UTL_FILE.PUT_LINE(id,name);
-- UTL_FILE.PUT(id,'It worked and wrote to this file');
UTL_FILE.FCLOSE(id);
DBMS_OUTPUT.PUT_LINE('Successful write to file');
EXCEPTION
WHEN OTHERS THEN
err := SQLERRM;
num := SQLCODE;
DBMS_OUTPUT.PUT_LINE(err);
DBMS_OUTPUT.PUT_LINE(num);
DBMS_OUTPUT.PUT_LINE('Error in writing to file');
END write_index; -
Can I create a file using pl/sql code in application server ?
Hi
I wanted to create a file(any kind of file .txt .csv .exe etc..) using pl/sql code in application server?
Please help me with an example...in this regard
Regards
Sa864334 wrote:
I wanted to create a file(any kind of file .txt .csv .exe etc..) using pl/sql code in application server?And how is this "file" to be delivered?
Files can be created by PL/SQL code and stored in the Oracle database as CLOBs. This a fairly easy and robust process. It runs entirely in the database. It conforms to transaction processing. The "file" (as a CLOB) resides in the database and can thus be secured via database security, is part of database backups and so on.
The basic issue is how to deliver the contents of the CLOB to the user. If via FTP, then the database can directly FTP the contents of the CLOB to the FTP server as a file. If via HTTP, the database can deliver the CLOB as a HTTP download directly to the web browser.
If the client is Java or .Net, then the CLOB contents can be delivered via SQL or DBMS_LOB or a custom PL/SQL interface.
In such cases, there is no need to step outside the secure and flexible database environment and create a physical o/s file in the wild (outside the controls of database security, data integrity and transaction processing). This is thus recommended and is the preference. -
Spool SQl data into text file using dynamic sql
Hi,
I am spooling output data into text file using command
select 'select t.mxname,bo.lxtype,t.mxrev'||chr(10)||'from mx_1234567'||chr(10)||
'where <condition>';
here mxname varchar(128),lxtype(128),mxrev(128) all are of varchar type.I want the output in format
e.g Part|1211121313|A
but due to column width the output,I am getting is with spaces.
"Part then blank spaces |1211121313 then blank spaces |A"
how can I remove these spaces between columns.I used set space 0 but not working.
Thanks in advance.
Your help will be appreciated.Hi Frank,
I have seen your reply for SET LINE SIZE function. But, I could not be able to understand it.
I am facing similar kind of issue in my present project.
I am trying spool more than 50 columns from a table into flat file. Because of more column lengths in few columns, i am getting space. There are so many columns with the same issue. I want to remove that space.so that, data can fit perfectly in one line in .txt file without any wrap text.
Below is my sample query.sql. Please let me know the syntax. My mail id : [email protected]
--Created : Sep 22,2008, Created By : Srinivasa Bojja
--Export all Fulfillments
--Scheduled daily after 1:00am and should complete before 3:30am
WHENEVER SQLERROR EXIT SQL.SQLCODE
SET LINESIZE 800
SET WRAP OFF
SET PAGESIZE 800
SET FEEDBACK OFF
SET HEADING ON
SET ECHO OFF
SET CONCAT OFF
SET COLSEP '|'
SET UNDERLINE OFF
SPOOL C:\Fulfillment.txt;
SELECT SRV.COMM_METHOD_CD AS Method,
SRV.SR_NUM AS "Fulfillment Row_Id",
CON.LAST_NAME AS "Filled By"
SRV.SR_TITLE AS Notes,
SRVXM.ATTRIB_04 AS "Form Description"
FROM SIEBEL.S_SRV_REQ SRV,
SIEBEL.S_SRV_REQ_XM SRVXM,
SIEBEL.S_USER USR,
SIEBEL.S_CONTACT CON
WHERE SRV.ROW_ID = SRVXM.PAR_ROW_ID AND
SRV.OWNER_EMP_ID = USR.ROW_ID AND
CON.ROW_ID= SRV.CST_CON_ID;
SPOOL OFF;
EXIT;
Maybe you are looking for
-
Can I add a larger hard drive to my macbook air?
I'm running into some limits on my air. It won't work for me to delete much of the data on the computer. TBH I'd rather not get an external drive if I can avoid it. Thanks for any help in advance.
-
BW Job Taking more time than normal execution time
Hi, Customer is trying to extract data from R/3 with BW OCPA Extractor. Selections within Infopackage under tab Data Selection are 0FISCPER = 010.2000 ZVKORG = DE Then it is scheduled (Info Package), after this monitor button is selected for the sche
-
System not listed in url iview property
hi all, I am creating an URL iview. In property editor of the URL iview I cannot see not even one system listed. I checked the system, its permission, it does have end user permission. Can anyone help me to view the system in the url iview property.
-
Dear All, I have freshly Installed SolMan 7.1. Now i want to generate the Solman Key regarding the same.Please provide me the steps regarding the same. And i want to know is IBM DB2 database supports Intel Processor? Because while Installing ECC 6.0
-
Dear experts Some client I'm working on has a line based item discount which will appear in the invoice as a separate discount line. The discount is defined as a 'PBH' - Price Break Headers However i can't find a way to differentiate this discount l