INSTR,SUBSTR
i have a problem in writing a query.
It is a simple select having a "IN" clause, the values of which are created dynamically.
Now since the IN clause could exceed 1000 values at a time, im using it as shown below
select * from table where (col1 in () or in () or in()....);
but my problem is that Im unable to set limit for values inside the IN clause.The values in the IN clause are in format ' %' i.e they are quoted and have a varaible length which Im trying to retrieve either thru INSTR or through SUBSTR.
I get these dynamic values in a varaible.Then i have to select the values for the IN clause from this variable.
Kindly help...its urgent
Why bother with instr/substr and the limitation of the IN clause?
Try to generate a select statement out of your csv format (lots of examples out there). One way could be:
SQL> var str varchar2(100)
SQL> var cur refcursor
SQL> exec :str := 'scott,james'
PL/SQL procedure successfully completed.
SQL> begin
open :cur for
select empno, ename from emp
where ename in (
select upper (t.column_value.extract ('//text()'))
from table(cast(xmlsequence(xmltype ('<d><d>'|| replace (:str, ',', '</d><d>') || '</d></d>').extract ('d/d')) as sys.xmlsequencetype)) t);
end;
PL/SQL procedure successfully completed.
SQL> print cur
EMPNO ENAME
7788 SCOTT
7900 JAMES
Similar Messages
-
Please help solve this question i am stuck on
We have the following value that we can use:
Numeric: 0-34 and 80-100 only
or Non Numberic X S U D- D D+
Have to use INSTR and SUBSTR functions to test that the value is a valid
(for now only trying to create a function which can later be put into a procedure.)
SELECT TO_NUMBER('12 ') //e.g HERE 12 and a space for the values as above
FROM DUAL
the where clause looks at all three spaces to make sure values are correct (given number or non-numberic values only)
(Hence if the number is true then number comes back (meaning true)
or it says NO rows)
If value is non numeric, test it to allow non numberic also.
I am completely unsure about it but tried this
SELECT TO_NUMBER('34 ')
FROM DUAL
WHERE INSTR('0123456789',1,1)<=9 (looking at first number ?)
AND
INSTR('0123456789',2,2)<=9
AND
INSTR('0123456789',3,3)=0;
Something like this has to be done.....subst (instr, x,x,) i think mite help.Why not use regular expressions? The below thread gives you an example and instructions on how to use.
alphanumeric validation -
Query Help... INSTR/SUBSTR/SUBSTR_REGEXTRACT
basically, I am trying to convert timezone of my incoming record from UTC to local timezone of the record. Essentially, I am going to do this from a lookup table that contains all the UTC conversions to local timezone.
so, if I have 3 possible patterns of of records:
(GMT-05:00) Eastern Time (US & Canada)
(GMT+02:00) Harare, Pretoria
(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London
and I want to get the numeric value (if available else 0)
so for the first record I would want -5
for the second recodr I want 2
for the third record I want 0
from my select query. how would I do that? ne ideas...with SQL query if possible..the DB is Oracle..
ne suggestions?Or
SQL> with t as (
select '(GMT-05:00) Eastern Time (US & Canada)' time_z from dual union
select '(GMT+02:00) Harare, Pretoria' from dual union
select '(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London' from dual
select time_z, nvl(to_number(regexp_substr(time_z, '[+-]\d+')),0) diff
from t
TIME_Z DIFF
(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London 0
(GMT+02:00) Harare, Pretoria 2
(GMT-05:00) Eastern Time (US & Canada) -5
3 rows selected. -
Using multiple xdofx commands together. For eg: substr and instr
Hi,
I am working in developing an RTF where a situation is to use xdofx:sustr and xdofx:instr together.
I tried but its not working properly.
Is there any special commands to use in such a scenario.
Thanks,
Anandplz post what are you doing
works for me
as example
<?xdofx:substr(substr(COLOR,5),instr(substr(COLOR,5),’;’)+1)?>for
<ROWSET>
<ROW>
<COLOR>qwe qwe;rty</COLOR>
</ROW>
</ROWSET>gives
rty -
Replace substr, instr with Reg_exp, is this possible,
Hi Team,
I have Small requirement below, i have writen Query For this but was thinking Is there Any better way Of
doing it, esp With Use To reg_exp,
i have Some code As shown below
'23456_TR_ABC_CODE12_JPM-(1)100-(1)150'
From this code i Only want portion which Is Between 'TR_' And '_CODE12' i.e. ABC,
given Is my Query And its output
Select
substr( substr('23456_TR_ABC_CODE12_JPM-(1)100-(1)150',instr('23456_TR_ABC_CODE12_JPM-(1)100-(1)150','TR_',1,1)+3),
1,
instr(
substr('23456_TR_ABC_CODE12_JPM-(1)100-(1)150',instr('23456_TR_ABC_CODE12_JPM-(1)100-(1)150','TR_',1,1)+3),
'_',1,1
-1) "word"
From dual;
word
1 ABC
kindly let me know If there Is Any better way Of doing it,,,Jeneesh, in case there are several TR_ or _CODE12 in the line I'd advice to use non-greedy operators.
SQL> with t as
2 (select '23456_TR_ABC_CODE12_JPM_(1)_100_CODE12_ASJ' word from dual)
3 select regexp_replace(word, '.*TR_<font color="red">(.*)</font>_CODE12.*', '\1') word
4 from t;
WORD
<font color="red">ABC_CODE12_JPM_(1)_100</font>
SQL>
It is working with (+) sign.
SQL> with t as
2 (select '23456_TR_ABC_CODE12_JPM_(1)_100_CODE12_ASJ' word from dual)
3 select regexp_replace(word, '.*TR_<font color="blue">(.+?)</font>_CODE12.*', '\1') word
4 from t;
WORD
<font color="blue">ABC</font>
SQL>
But I don't understand why it is not working with (*) sign :((
SQL> with t as
2 (select '23456_TR_ABC_CODE12_JPM_(1)_100_CODE12_ASJ' word from dual)
3 select regexp_replace(word, '.*TR_<font color="green">(.*?)</font>_CODE12.*', '\1') word
4 from t;
WORD
<font color="green">ABC_CODE12_JPM_(1)_100</font>Maybe someone can explain?
Several more examples:
the first and the last of them are really strange, at least for me:
SQL> with t as
2 (select '23456_TR_ABC_CODE12_JPM_(1)_100_CODE12_ASJ' word from dual)
3 select regexp_replace(word, '^<font color="red">.*</font>TR_<font color="red">(.*?)</font>_CODE12.*$', '\1') word
4 from t;
WORD
<font color="red">ABC_CODE12_JPM_(1)_100</font>
SQL>
SQL> with t as
2 (select '23456_TR_ABC_CODE12_JPM_(1)_100_CODE12_ASJ' word from dual)
3 select regexp_replace(word, '^<font color="blue">.*?</font>TR_<font color="blue">(.*?)</font>_CODE12.*$', '\1') word
4 from t;
WORD
<font color="blue">ABC</font>
SQL>
SQL> with t as
2 (select '23456_TR_ABC_CODE12_JPM_(1)_100_CODE12_ASJ' word from dual)
3 select regexp_replace(word, '^<font color="red">.*?</font>TR_<font color="red">(.*)</font>_CODE12.*$', '\1') word
4 from t;
WORD
<font color="red">ABC</font>
SQL> -
Like is not working with substr...
Hello,
I am trying to do
FOR i IN (SELECT grp.group_id
FROM ems.groups grp, ems.groups_loc gl, ems.location loc
WHERE grp.group_id = gl.group_id
AND loc.loc_id = gl.loc_id
AND gl.loc_id = i_loc_id
AND (UPPER(group_desc) LIKE (UPPER(SUBSTR (location_desc, 3,INSTR(SUBSTR(location_desc,3,LENGTH(location_desc)),',')-1)) || ' IT')
OR UPPER(group_desc) LIKE (UPPER(SUBSTR (location_desc, 3,INSTR(SUBSTR(location_desc,3,LENGTH(location_desc)),',')-1)) || ' FACILITIES' ))
) LOOP
Here there is data with UPPER(SUBSTR (location_desc, 3,INSTR(SUBSTR(location_desc,3,LENGTH(location_desc)),',')-1)) || ' IT') as well as (UPPER(SUBSTR (location_desc, 3,INSTR(SUBSTR(location_desc,3,LENGTH(location_desc)),',')-1)) || ' FACILITIES' )),
But it seems to be 'LIKE' is not working.
Can please anybody help me with this problem.
Thanks.Sorry, for insufficient information.
here i have location desc as 39 Herndon, VA, 11 Jacksonville, FL, 48 Pittsburgh, PA. From these description i have to get Herndon, Jacksonville, Pittsburgh and then check group_desc = 'HERNDONIT' OR 'HERNDON FACILITIES'.
I am trying with,
(UPPER(group_desc) LIKE (UPPER(SUBSTR (location_desc, 3,INSTR(SUBSTR(location_desc,3,LENGTH(location_desc)),',')-1)) || ' IT'|| '%')
OR UPPER(group_desc) LIKE (UPPER(SUBSTR (location_desc, 3,INSTR(SUBSTR(location_desc,3,LENGTH(location_desc)),',')-1)) || ' FACILITIES' || '%' ))
But its not working correctly. Eventhough there is data i am not getting any row return.
Thanks,
Gayatri. -
Good morning...
I got a sub sequence of a string... n now I'm trying to use this sub string as a string... but the javac only tells me a warning like incompatible types...
inputLine.subSequence(tamanho-contador,tamanho-(contador-5))
I tryed to convert that charSequence (that java says me) and convert to a string.. but it brings me that java.lang.Object cannot be applied to java.lang.charSequence
How may I do to take that substring n use like another independent string?
I would like to put more three chars before convert it.
Like:
abc123def
I took c123d using subSequence n I want to put more three chars "jav" to finally my string stay like c123djav
How may I do to put more chars n convert it to a String? (In start I was suposed that the substring was a string... but it makes me an error....)
Thanks...Ok... I used that
String anT = inStr.substring(inStr.indexOf('c'), inStr.length()-2)+"jav";
But it makes a warning like:
subSequence(int,int) in java.lang.String cannot be applied to (int, java.lang.String)
I think I need to mix the "jav" after take the string... c123d ... but even only taking that subSequence, and trying to put in a string, I have a warning like:
incompatible types
found: java.lang.charSequence
required: java.lang.String -
Dear all,
I have a string that will spool to a file from sql*plus, and the string maybe more than 255 characters, e.g.:
v_sql := 'select surname, firstname, sex, birth,
address1, address2,
address3, ..., .... from employee;'
dbms_output.put_line(v_sql);
Now, I want to chop the string in several lines when 'meet' the comma ',' , the output I want become to, e.g.:
dbms_output.put_line('select surname,');
dbms_output.put_line('firstname,');
dbms_output.put_line('sex,');
dbms_output.put_line('... from employee;');
So, I use the loop and instr in a procedure:
procedure xxx (p_sql in varchar2) is
v_len number := length(p_sql);
v_comma number := 0;
v_next_comma number := 0;
v_string varchar2(1000);
begin
for v_cnt in 1..v_len loop
if v_comma = 0 then
v_comma := instr(p_sql, ',');
v_string := substr(p_sql, 1, v_comma-1);
dbms_output.put_line(v_string);
else
v_comma := instr(p_sql, ',');
v_next_comma := instr(substr(p_sql, v_comma+1, v_len-v_comma), ',');
v_string := substr(p_sql, v_comma+1, v_next_comma-1);
dbms_output.put_line(v_string);
end if;
if v_comma > 0 and v_next_comma = 0 then
v_cnt := v_comma +1; <--- v_cnt will not change
elsif v_next_comma > 0 then
v_cnt := v_next_comma +1;
end if;
end loop;
end xxx;
From the above coding, however, I found a problem that v_cnt will not skip to the 'comma' position. And I feel that it is not efficient if the length of the string is very long...
So, is there another way to do? Please help. Thank you!
Remarks: Database 10g.
Regards.yes, it would see that you aren't running 10r2. here is the code you need
http://www.oraclecommunity.net/group/sqlplus/forum/topic/show?id=1988559%3ATopic%3A9386
the file - vsql.sql - is attached at the end. instead of using a cursor loop (curr_sql in my code) to get a statement, you'll just use your sql statement already in a variable. it's a simple procedure - breaks on certain keywords, or delimiters (like commas) before the linessize (132) is reached, and dbms_outputs the text.
changing the end of script to use a static sql statement:
begin
my_stmt := 'MERGE /*+ dynamic_sampling(ST 4) dynamic_sampling_est_cdn(ST) */ INTO STATS_TARG'||
'ET$ ST USING (SELECT STALENESS, OSIZE, OBJ#, TYPE#, CASE WHEN STALENESS > .5 THE'||
'N 128 ELSE 0 END + AFLAGS AFLAGS, STATUS, SID, SERIAL#, PART#, BO# FROM ( SELECT'||
' /*+ no_expand dynamic_sampling(4) dynamic_sampling_est_cdn */ DECODE(BITAND(T.F'||
'LAGS,16), 16, ROUND( LOG(0.01, NVL( LEAST( 100, GREATEST( 0.01, (DECODE(BITAND(M'||
'.FLAGS, 1), 1, GREATEST(T.ROWCNT, M.INSERTS), LEAST((M.INSERTS + M.DELETES ';
sql_frmt ( my_stmt, save_line, prefix );
if (save_line is not null) then
dbms_output.put_line( prefix || save_line );
save_line := null;
end if;
end;
MERGE /*+ dynamic_sampling ( ST 4 ) dynamic_sampling_est_cdn ( ST ) */ INTO STATS_TARGET$ ST USING (
SELECT STALENESS, OSIZE, OBJ#, TYPE#, CASE WHEN STALENESS > .5 THEN 128 ELSE 0 END + AFLAGS AFLAGS, STATUS, SID, SERIAL#, PART#,
BO#
FROM (
SELECT /*+ no_expand dynamic_sampling ( 4 ) dynamic_sampling_est_cdn */ DECODE ( BITAND ( T.FLAGS, 16 ), 16, ROUND ( LOG ( 0.01,
NVL ( LEAST ( 100, GREATEST ( 0.01, ( DECODE ( BITAND ( M.FLAGS, 1 ), 1, GREATEST ( T.ROWCNT, M.INSERTS ), LEAST ( ( M.INSERTS
+ M.DELETES -
Hi all,
I am developing an application but there is a error in my code i culdnt find so far. Can anyone help?
I want to write to a .xml file in web server with servlet from remote. My code is
private static String message = "Error during Servlet processing";
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// response.setContentType("text/html;charset=UTF-8");
try {
int len = request.getContentLength();
byte[] input = new byte[len];
ServletInputStream sin = request.getInputStream();
int c, count = 0;
while ((c = sin.read(input, count, input.length - count)) != -1) {
count += c;
sin.close();
String inString = new String(input);
int index = inString.indexOf("/n");
if (index == -1) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(message);
response.getWriter().close();
return;
String user = inString.substring(0, index);
String data = inString.substring(index + 2);
//decode application/x-www-form-urlencoded string
// String decodedUser = URLDecoder.decode(user, "UTF-8");
// String decodedData = URLDecoder.decode(data, "UTF-8");
// int i = decodedData.indexOf("/n");
// String user = decodedData.substring(0, i);
// String db = decodedData.substring(i + 2, decodedData.length());
String result = "no";
// response.setContentType("text/html");
String filename = "/WEB-INF/" + user + ".xml";
// String pathName = getServletContext ( ) .getRealPath ( "/" + filename ) ;
// String contentType = getServletContext ( ) .getMimeType ( pathName ) ;
// if ( contentType != null )
// response.setContentType ( contentType ) ;
// else
// response.setContentType ( "application/octet-stream" ) ;
try {
OutputStream fcheck = null;
byte[] buf = data.getBytes();
fcheck = new FileOutputStream(filename);
for (int i = 0; i < buf.length; i++) {
fcheck.write(buf);
result = "yes";
} catch (IOException ex) {
Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
result = "no";
// ServletContext context = getServletContext();
// set the response code and write the response data
response.setStatus(HttpServletResponse.SC_OK);
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
writer.write(result);
writer.flush();
writer.close();
} catch (IOException e) {
try {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(e.getMessage());
response.getWriter().close();
} catch (IOException ioe) {
ý am sending data from remote as a string and want to write it in xml. But it is not working. Where am i wrong?I fixed it. But now it doesnt write to file and there is no error. So i cant find where am a wrong.
I send a request, it is taking string but it is not writing to file eventhough it is entering the try block.
Why it isnt writing? Is not servlet let it to write to file. My working code is here
private static String message = "Error during Servlet processing";
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
int len = request.getContentLength();
byte[] input = new byte[len];
ServletInputStream sin = request.getInputStream();
int c, count = 0;
while ((c = sin.read(input, count, input.length - count)) != -1) {
count += c;
sin.close();
String inString = new String(input);
int index = inString.indexOf("/n");
if (index == -1) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(message);
response.getWriter().close();
return;
String user = inString.substring(0, index);
String data = inString.substring(index + 2);
//decode application/x-www-form-urlencoded string
// String decodedUser = URLDecoder.decode(user, "UTF-8");
String decodedData = URLDecoder.decode(data, "UTF-8");
// int i = decodedData.indexOf("/n");
// String user = decodedData.substring(0, i);
// String db = decodedData.substring(i + 2, decodedData.length());
String result = "no";
String filename = user + ".xml";
try {
OutputStream fcheck = null;
byte[] buf = decodedData.getBytes();
fcheck = new FileOutputStream(filename);
for (int i = 0; i < buf.length; i++) {
fcheck.write(buf);
// char buffer[]=new char[data.length()];
// data.getChars(0, data.length(), buffer, 0);
// FileWriter f0=new FileWriter(filename);
// for(int i=0;i<buffer.length;i++){
// f0.write(buffer[i]);
result = "yes";
} catch (IOException ex) {
Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
result = "no";
// ServletContext context = getServletContext();
// set the response code and write the response data
response.setStatus(HttpServletResponse.SC_OK);
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
writer.write(result);
writer.flush();
writer.close();
} catch (IOException e) {
try {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(e.getMessage());
response.getWriter().close();
} catch (IOException ioe) { -
Writing from a text file into a table
Hi,
I have a problem with dearchiving the data from the txt file to the respective table.
The table name is dynamic & I get the required columns from all_tab_columns.
I use UTL_FILE.GET_LINE() to get the data one line at a time and INSTR() & SUBSTR() to break them into the respective columns.
My dynamic insert contains a set of bind variables equal to the no. of columns of the table.
The statement gets constructed correctly but I tried to use execute_immediate , i realised that i cannot construct the USING clause for it & hence I switced to DBMS_SQL.
The DBMS_SQL.BIND_VARIABLE() binds all of the bind variables to a table of varchar2. I've taken care to convert the date & the number variables while binding.
When i do DBMS_SQL.EXECUTE() I get the error,
ORA-01008 Not all variables bound .
I don't know the reason since the no. of bind variables & the no. of table variables are the same & the value in the table looks fine too!
Could this be a date issue ??? am using the default format DD-MON-YY both to write to the text file and to read from it.
Any help would be appreciated.
thx
kalpana
Part of the code :
Begin
destination_file := upper(p_table_name)||'_ARCH'||to_char
(p_process_date,'yyyymmdd')||'.dat';
dbms_output.put_line(destination_file);
file_id := UTL_FILE.FOPEN(file_path, destination_file,'r');
-- Get the number of columns in the table to be archived
select count(column_name)
into col_ctr
from all_tab_columns
where table_name = upper(p_table_name)
order by column_name;
sql_stmt1 := 'Insert into '||p_table_name||'(';
sql_stmt2 := ' values(';
For col_rec in column_cur loop
if col_ctr = column_cur%rowcount then -- last column in
the select statement
sql_stmt1 := sql_stmt1 || col_rec.column_name;
sql_stmt2 := sql_stmt2||':b'||column_cur%rowcount;
else
sql_stmt1 := sql_stmt1 || col_rec.column_name ||',';
sql_stmt2 := sql_stmt2||':b'||column_currowcount||',';
end if;
type_rec(column_cur%rowcount) := col_rec.data_type;
end loop;
sql_stmt1 := sql_stmt1||')';
sql_stmt2 := sql_stmt2||')';
sql_stmt := sql_stmt1||sql_stmt2;
loop
Begin
UTL_FILE.GET_LINE(file_id,v_column_value);
For i in 1..col_ctr loop
v_next_position := INSTR(v_column_value,';',1,i);
if i = 1 then
v_rec(i) := SUBSTR(v_column_value, v_prev_position, v_next_position - 1);
elsif i = col_ctr then -- last but one column
v_rec(i) := SUBSTR(v_column_value, v_prev_position);
else
v_rec(i) := SUBSTR(v_column_value, v_prev_position, (v_next_position - v_prev_position));
end if;
v_prev_position := v_next_position + 1;
end loop;
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, sql_stmt, dbms_sql.native);
For i in 1..col_ctr loop
if type_rec(i) = 'DATE' then
DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||i, to_date(v_rec(i),'DD-MON-YY'));
elsif type_rec(i) = 'NUMBER' then
DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||i, to_number(v_rec(i)));
end if;
end loop;
-- Insert the row into the history table
-- execute immediate sql_stmt USING value(v_rec);
v_dummy := DBMS_SQL.EXECUTE(v_cursor);
if SQL%NOTFOUND then
dbms_output.put_line('CPN_HISTORY_ARCHIVE_PKG.DEARCHIVE_DATA : No records to insert');
end if;
Exception -- for UTL_FILE.GET_LINE
when NO_DATA_FOUND then
DBMS_SQL.CLOSE_CURSOR(v_cursor);
UTL_FILE.FCLOSE(file_id);
exit;
End;
end loop; -- end of loop for UTL_FILE.GET_LINE
DBMS_SQL.CLOSE_CURSOR(v_cursor);
UTL_FILE.FCLOSE(file_id);your program is currect except u r not building bind variables for varchar2 columns
declare
type tab133 is table of varchar2(4000) index by binary_integer;
file_id utl_file.file_type;
sql_stmt1 varchar2(1000);
sql_stmt2 varchar2(1000);
v_column_value varchar2(1000);
sql_stmt varchar2(2000);
col_ctr number:=0;
p_table_name varchar2(30):='emp1';
cursor column_cur is select column_name,data_type from user_tab_columns
where table_name=upper(p_table_name);
mainstr VARCHAR2(40) := '';
splitstr VARCHAR2(30) := '';
l_count NUMBER(20) := 1;
itr_count NUMBER(20) := 0;
processed BOOLEAN := FALSE;
v_rec tab133;
type_rec tab133;
v_cursor integer;
column_currowcount number;
v_dummy number:=0;
Begin
--dbms_output.put_line(destination_file);
file_id := UTL_FILE.FOPEN('c:\suresh', 'emp.txt','r');
-- Get the number of columns in the table to be archived
select count(column_name)
into col_ctr
from user_tab_columns
where table_name = upper(p_table_name)
order by column_name;
sql_stmt1 := 'Insert into '||p_table_name||'(';
sql_stmt2 := ' values(';
For col_rec in column_cur loop
if col_ctr = column_cur%rowcount then
sql_stmt1 := sql_stmt1 || col_rec.column_name;
sql_stmt2 := sql_stmt2||':b'||column_cur%rowcount;
else
sql_stmt1 := sql_stmt1 || col_rec.column_name ||',';
sql_stmt2 := sql_stmt2||':b'||column_cur%rowcount||',';
end if;
type_rec(column_cur%rowcount) := col_rec.data_type;
end loop;
sql_stmt1 := sql_stmt1||')';
sql_stmt2 := sql_stmt2||')';
sql_stmt := sql_stmt1||sql_stmt2;
dbms_output.put_line(sql_stmt);
loop
Begin
UTL_FILE.GET_LINE(file_id,v_column_value);
itr_count := 0;
l_count :=1;
processed := FALSE;
mainstr:=v_column_value;
LOOP
itr_count := itr_count+1;
IF instr(mainstr,',',1,itr_count)>0 THEN
splitstr := SUBSTR(mainstr,l_count,(INSTR(mainstr,',',1,itr_count)-l_count));
l_count := INSTR(mainstr,',',1,itr_count)+1;
ELSE
splitstr := SUBSTR(mainstr,l_count,LENGTH(mainstr)+1-l_count);
processed := TRUE;
END IF;
v_rec(itr_count):=splitstr;
IF processed THEN
EXIT ;
END IF;
END LOOP;
v_cursor := DBMS_SQL.OPEN_CURSOR;
--dbms_output.put_line(col_ctr);
DBMS_SQL.PARSE(v_cursor, sql_stmt, dbms_sql.native);
For i in 1..col_ctr loop
if type_rec(i) = 'DATE' then
DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||to_char(i), to_date(v_rec(i),'DD/mm/yyyy'));
elsif type_rec(i) = 'NUMBER' then
DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||to_char(i), to_number(v_rec(i)));
elsif type_rec(i) = 'VARCHAR2' then
DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||to_char(i), v_rec(i));
end if;
end loop;
v_dummy := DBMS_SQL.EXECUTE(v_cursor);
if SQL%NOTFOUND then
dbms_output.put_line('CPN_HISTORY_ARCHIVE_PKG.DEARCHIVE_DATA : No records to insert');
end if;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
Exception
when NO_DATA_FOUND then
UTL_FILE.FCLOSE(file_id);
exit;
End;
end loop;
UTL_FILE.FCLOSE(file_id);
EXCEPTION
when others then
dbms_output.put_line(sqlerrm);
UTL_FILE.FCLOSE(file_id);
END;
TEST:
SQL> DESC EMP1
Name Null? Type
ENAME VARCHAR2(15)
SUBJ VARCHAR2(15)
SDATE DATE
DATA FILE:
AABC,oracle,08/08/2001
xyz,social,12/12/2001
SQL> select * from emp1;
ENAME SUBJ SDATE
AABC oracle 08/08/2001 00:00:00
xyz social 12/12/2001 00:00:00 -
Need Help to see why the performance is not good
Hi,
We have an application that all process are developed in PL/SQL on Oracle 9i Database :
Oracle9i Enterprise Edition Release 9.2.0.6.0 - 64bit Production
PL/SQL Release 9.2.0.6.0 - Production
Why I have created this package. the application is a production management on chemical industries. I need to sometimes trace the Manufacturing order execution to eventually answer some incoherent data. If I analyze directly the data in the Table is not always responding because the origin of problem can be provide of some execution that perform some calculation.
In the procedure or function a use my package PAC_LOG_ERROR.PUT_LINE(xxxxxx) to save the information. This command save the information in the memory before. At the end of the procedure or function a perform the insert with the COMMIT calling PAC_LOG_ERROR.LOGS or PAC_LOG_ERROR.ERRORS on the catch exception.
This package is always call. On each routines performed I execute it. In the trace log of the database we have see a problem we the procedure GET_PROC_NAME in the package. We have identify that is called more that 800x and increase the performance. Who increase is this select command :
SELECT * INTO SOURCE_TEXT
FROM (SELECT TEXT FROM all_source
WHERE OWNER = SOURCE_OWNER AND
NAME=SOURCE_NAME AND
TYPE IN ('PROCEDURE','FUNCTION','PACKAGE BODY') AND
LINE <= SOURCE_LINE AND SUBSTR(TRIM(TEXT),1,9) IN ('PROCEDURE','FUNCTION ')
ORDER BY LINE DESC)
WHERE ROWNUM = 1;I use it to get the procedure or function name where my log proc is called. I now that I can pass in parameters, but I have think to use an automatic method, that can help to not have some problem with others developer team to make a copy/past and not update the parameters. Because the Log info is read by the Help Desk and if we have an error on the information, it not a good help.
COULD YOU PLEASE HELP ME TO OPTIMIZE OR SAID THE BETTER METHOD TO DO IT ?
Here my package :
create or replace
PACKAGE PAC_LOG_ERROR AS
-- Name : pac_log_error.sql
-- Author : Calà Salvatore - 02 July 2010
-- Description : Basic Error and Log management.
-- Usage notes : To active the Log management execute this statement
-- UPDATE PARAM_TECHNIC SET PRM_VALUE = 'Y' WHERE PRM_TYPE = 'TRC_LOG';
-- COMMIT;
-- To set the period in day before to delete tracability
-- UPDATE PARAM_TECHNIC SET PRM_VALUE = 60 WHERE PRM_TYPE = 'DEL_TRC_LOG';
-- COMMIT;
-- To set the number in day where the ERROR is save before deleted
-- UPDATE PARAM_TECHNIC SET PRM_VALUE = 60 WHERE PRM_TYPE = 'DEL_TRC_LOG';
-- COMMIT;
-- Requirements : Packages PAC_PUBLIC and OWA_UTIL
-- Revision History
-- --------+---------------+-------------+--------------------------------------
-- Version | Author | Date | Comment
-- --------+---------------+-------------+--------------------------------------
-- 1.0.0 | S. Calà | 02-Jul-2010 | Initial Version
-- --------+---------------+-------------+--------------------------------------
-- | | |
-- --------+---------------+-------------+--------------------------------------
PROCEDURE INITIALIZE;
PROCEDURE CLEAN;
PROCEDURE RESETS(IN_SOURCE IN VARCHAR2 DEFAULT NULL);
PROCEDURE PUT_LINE(TXT IN VARCHAR2);
PROCEDURE ERRORS(REF_TYPE IN VARCHAR2 DEFAULT 'SITE', REF_VALUE IN VARCHAR2 DEFAULT '99', ERR_CODE IN NUMBER DEFAULT SQLCODE, ERR_MSG IN VARCHAR2 DEFAULT SQLERRM);
PROCEDURE LOGS(REF_TYPE IN VARCHAR2 DEFAULT 'SITE', REF_VALUE IN VARCHAR2 DEFAULT '99');
END PAC_LOG_ERROR;
create or replace
PACKAGE BODY PAC_LOG_ERROR
AS
/* Private Constant */
CR CONSTANT CHAR(1) := CHR(13); -- Retour chariot
LF CONSTANT CHAR(1) := CHR(10); -- Saut de ligne
CR_LF CONSTANT CHAR(2) := LF || CR; --Saut de ligne et retour chariot
TAB CONSTANT PLS_INTEGER := 50;
sDelay CONSTANT PLS_INTEGER := 30;
/* Private Record */
TYPE REC_LOG IS RECORD(
ERR_DATE TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
ERR_TXT VARCHAR2(4000)
/* Private Type Table */
TYPE TAB_VALUE IS TABLE OF REC_LOG INDEX BY PLS_INTEGER;
TYPE TAB_POINTER IS TABLE OF TAB_VALUE INDEX BY VARCHAR2(80);
/* Private Variables Structures */
LOG_TRC PARAM_TECHNIC.PRM_VALUE%TYPE;
LIST_PARAM TAB_POINTER;
/* Private Programs */
FUNCTION GET_PROC_NAME( SOURCE_OWNER IN all_source.OWNER%TYPE
,SOURCE_NAME IN all_source.NAME%TYPE
,SOURCE_LINE IN all_source.LINE%TYPE) RETURN VARCHAR2
AS
SOURCE_TEXT all_source.TEXT%TYPE;
TYPE RECORD_TEXT IS TABLE OF all_source.TEXT%TYPE;
RETURN_TEXT RECORD_TEXT;
BEGIN
SELECT * INTO SOURCE_TEXT
FROM (SELECT TEXT FROM all_source
WHERE OWNER = SOURCE_OWNER AND
NAME=SOURCE_NAME AND
TYPE IN ('PROCEDURE','FUNCTION','PACKAGE BODY') AND
LINE <= SOURCE_LINE AND SUBSTR(TRIM(TEXT),1,9) IN ('PROCEDURE','FUNCTION ')
ORDER BY LINE DESC)
WHERE ROWNUM = 1;
IF SOURCE_TEXT IS NOT NULL OR SOURCE_TEXT != '' THEN
SOURCE_TEXT := TRIM(SUBSTR(SOURCE_TEXT,1,INSTR(SOURCE_TEXT,'(')-1));
SOURCE_TEXT := LTRIM(LTRIM(TRIM(SOURCE_TEXT),'PROCEDURE'),'FUNCTION');
SOURCE_TEXT := SOURCE_NAME||'.'|| TRIM(SOURCE_TEXT);
ELSE
SOURCE_TEXT := 'ANONYMOUS BLOCK';
END IF;
RETURN SOURCE_TEXT;
END GET_PROC_NAME;
PROCEDURE SELECT_MASTER(REF_TYPE IN VARCHAR2, PARAM_VALUE IN VARCHAR2, SITE OUT VARCHAR2, REF_MASTER OUT VARCHAR2)
AS
BEGIN
REF_MASTER := '';
SITE := '99';
CASE UPPER(REF_TYPE)
WHEN 'PO' THEN -- Process Order
SELECT SITE_CODE INTO SITE FROM PO_PROCESS_ORDER WHERE PO_NUMBER = PARAM_VALUE;
WHEN 'SO' THEN -- Shop Order
SELECT P.SITE_CODE,P.PO_NUMBER INTO SITE,REF_MASTER FROM SO_SHOP_ORDER S
INNER JOIN PO_PROCESS_ORDER P ON P.PO_NUMBER = S.PO_NUMBER
WHERE S.NUMOF = PARAM_VALUE;
WHEN 'SM' THEN -- Submixing
SELECT SITE_CODE,NUMOF INTO SITE,REF_MASTER FROM SO_SUBMIXING WHERE IDSM = PARAM_VALUE;
WHEN 'IDSM' THEN -- Submixing
SELECT SITE_CODE,NUMOF INTO SITE,REF_MASTER FROM SO_SUBMIXING WHERE IDSM = PARAM_VALUE;
WHEN 'PR' THEN -- Pourring
SELECT B.SITE_CODE,P.NUMOF INTO SITE,REF_MASTER FROM SO_POURING P
INNER JOIN SO_SUBMIXING B ON B.IDSM=P.IDSM
WHERE P.IDSM = PARAM_VALUE;
WHEN 'NUMSMP' THEN -- Pourring
SELECT SITE_CODE,NUMOF INTO SITE,REF_MASTER FROM SAMPLE WHERE NUMSMP = TO_NUMBER(PARAM_VALUE);
-- WHEN 'MSG' THEN -- Messages
-- SELECT SITE_CODE,PO_NUMBER INTO SITE,REF_MASTER FROM CMS_INTERFACE.MAP_ITF_PO WHERE MSG_ID = PARAM_VALUE;
ELSE
SITE := sys_context('usr_context', 'site_attribute');
END CASE;
EXCEPTION
WHEN OTHERS THEN
REF_MASTER := '';
SITE := sys_context('usr_context', 'site_attribute');
END SELECT_MASTER;
PROCEDURE ADD_LIST_PROC
AS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
MERGE INTO LOG_PARAM A
USING (SELECT OWNER, TYPE
,NAME PROC
, CASE NAME WHEN SUBNAME THEN NULL
ELSE SUBNAME
END SUBPROC
FROM (
SELECT owner,TYPE,UPPER(NAME) NAME,UPPER(trim(substr(substr(trim(text),1,instr(trim(text),'(')-1),instr(substr(trim(text),1,instr(trim(text),'(')-1),' ')))) SUBNAME
FROM ALL_SOURCE where owner in ('CMS_ADM','CMS_INTERFACE')
and type in ('FUNCTION','PROCEDURE','PACKAGE BODY')
and (instr(substr(trim(text),1,instr(trim(upper(text)),'(')-1),'FUNCTION') = 1 or instr(substr(trim(text),1,instr(trim(upper(text)),'(')-1),'PROCEDURE')=1)
)-- ORDER BY OWNER,PROC,SUBPROC NULLS FIRST
) B
ON (A.OWNER = B.OWNER AND A.TYPE = B.TYPE AND A.PROC=B.PROC AND NVL(A.SUBPROC,' ') = NVL(B.SUBPROC,' '))
WHEN NOT MATCHED THEN
INSERT (OWNER,TYPE,PROC,SUBPROC) VALUES (B.OWNER,B.TYPE,B.PROC,B.SUBPROC)
WHEN MATCHED THEN
UPDATE SET ACTIVE = ACTIVE;
DELETE LOG_PARAM A
WHERE NOT EXISTS (SELECT OWNER, TYPE
,NAME PROC
, CASE NAME WHEN SUBNAME THEN NULL
ELSE SUBNAME
END SUBPROC
FROM (
SELECT owner,TYPE,NAME,upper(trim(substr(substr(trim(text),1,instr(trim(text),'(')-1),instr(substr(trim(text),1,instr(trim(text),'(')-1),' ')))) SUBNAME
FROM ALL_SOURCE where owner in ('CMS_ADM','CMS_INTERFACE')
and type in ('FUNCTION','PROCEDURE','PACKAGE BODY')
and (instr(substr(trim(text),1,instr(trim(text),'(')-1),'FUNCTION') = 1 or instr(substr(trim(text),1,instr(trim(text),'(')-1),'PROCEDURE')=1)
) WHERE A.OWNER = OWNER AND A.TYPE = TYPE AND A.PROC=PROC AND NVL(A.SUBPROC,' ') = NVL(SUBPROC,' '));
COMMIT;
EXCEPTION
WHEN OTHERS THEN
NULL;
END ADD_LIST_PROC;
PROCEDURE INITIALIZE
AS
BEGIN
LIST_PARAM.DELETE;
CLEAN;
-- ADD_LIST_PROC;
EXCEPTION
WHEN OTHERS THEN
NULL;
END INITIALIZE;
PROCEDURE CLEAN
AS
PRAGMA AUTONOMOUS_TRANSACTION;
dtTrcLog DATE;
dtTrcErr DATE;
BEGIN
BEGIN
SELECT dbdate-NUMTODSINTERVAL(to_number(PRM_VALUE),'DAY') INTO dtTrcLog
FROM PARAM_TECHNIC WHERE PRM_TYPE = 'DEL_TRC_LOG';
EXCEPTION
WHEN OTHERS THEN
dtTrcLog := dbdate -NUMTODSINTERVAL(sDelay,'DAY');
END;
BEGIN
SELECT dbdate-NUMTODSINTERVAL(to_number(PRM_VALUE),'DAY') INTO dtTrcErr
FROM PARAM_TECHNIC WHERE PRM_TYPE = 'DEL_TRC_ERR';
EXCEPTION
WHEN OTHERS THEN
dtTrcErr := dbdate -NUMTODSINTERVAL(sDelay,'DAY');
END;
DELETE FROM ERROR_LOG WHERE ERR_TYPE ='LOG' AND ERR_DATE < dtTrcLog;
DELETE FROM ERROR_LOG WHERE ERR_TYPE ='ERROR' AND ERR_DATE < dtTrcErr;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
NULL; -- Do nothing if error occurs and catch exception
END CLEAN;
PROCEDURE RESETS(IN_SOURCE IN VARCHAR2 DEFAULT NULL)
AS
SOURCE_OWNER all_source.OWNER%TYPE;
SOURCE_NAME all_source.NAME%TYPE;
SOURCE_LINE all_source.LINE%TYPE;
SOURCE_TEXT all_source.TEXT%TYPE;
SOURCE_PROC VARCHAR2(32727);
BEGIN
OWA_UTIL.WHO_CALLED_ME(owner => SOURCE_OWNER,
name => SOURCE_NAME,
lineno => SOURCE_LINE,
caller_t => SOURCE_TEXT);
IF SOURCE_PROC IS NULL THEN
SOURCE_PROC := SUBSTR(GET_PROC_NAME(SOURCE_OWNER,SOURCE_NAME,SOURCE_LINE),1,125);
ELSE
SOURCE_PROC := IN_SOURCE;
END IF;
LIST_PARAM.DELETE(SOURCE_PROC);
EXCEPTION
WHEN OTHERS THEN
NULL;
END RESETS;
PROCEDURE PUT_LINE(TXT IN VARCHAR2)
AS
PRAGMA AUTONOMOUS_TRANSACTION;
SOURCE_OWNER all_source.OWNER%TYPE;
SOURCE_NAME all_source.NAME%TYPE;
SOURCE_LINE all_source.LINE%TYPE;
SOURCE_TEXT all_source.TEXT%TYPE;
SOURCE_PROC VARCHAR2(128);
BEGIN
IF TXT IS NULL OR TXT = '' THEN
RETURN;
END IF;
OWA_UTIL.WHO_CALLED_ME(owner => SOURCE_OWNER,
name => SOURCE_NAME,
lineno => SOURCE_LINE,
caller_t => SOURCE_TEXT);
SOURCE_PROC := GET_PROC_NAME(SOURCE_OWNER,SOURCE_NAME,SOURCE_LINE);
IF LIST_PARAM.EXISTS(SOURCE_PROC) THEN
LIST_PARAM(SOURCE_PROC)(LIST_PARAM(SOURCE_PROC).COUNT+1).ERR_TXT := TXT;
ELSE
LIST_PARAM(SOURCE_PROC)(1).ERR_TXT := TXT;
END IF;
EXCEPTION
WHEN OTHERS THEN
NULL;
END PUT_LINE;
PROCEDURE LOGS(REF_TYPE IN VARCHAR2 DEFAULT 'SITE', REF_VALUE IN VARCHAR2 DEFAULT '99')
AS
PRAGMA AUTONOMOUS_TRANSACTION;
MASTER_VALUE ERROR_LOG.ERR_MASTER%TYPE;
SITE PARAMTAB.SITE_CODE%TYPE;
SOURCE_OWNER all_source.OWNER%TYPE;
SOURCE_NAME all_source.NAME%TYPE;
SOURCE_LINE all_source.LINE%TYPE;
SOURCE_TEXT all_source.TEXT%TYPE;
SOURCE_PROC VARCHAR2(128);
ERR_KEY NUMBER;
BEGIN
-- NULL;
OWA_UTIL.WHO_CALLED_ME(owner => SOURCE_OWNER,
name => SOURCE_NAME,
lineno => SOURCE_LINE,
caller_t => SOURCE_TEXT);
SOURCE_PROC := SUBSTR(GET_PROC_NAME(SOURCE_OWNER,SOURCE_NAME,SOURCE_LINE),1,128);
LIST_PARAM.DELETE(SOURCE_PROC);
-- SELECT NVL(MAX(ACTIVE),'N') INTO LOG_TRC FROM LOG_PARAM WHERE TRIM(UPPER((PROC||'.'||SUBPROC))) = TRIM(UPPER(SOURCE_PROC))
-- AND OWNER =SOURCE_OWNER AND TYPE = SOURCE_TEXT ;
-- IF LOG_TRC = 'N' THEN
-- LIST_PARAM.DELETE(SOURCE_PROC);
-- RETURN;
-- END IF;
-- SELECT_MASTER(REF_TYPE => UPPER(REF_TYPE), PARAM_VALUE => REF_VALUE, SITE => SITE, REF_MASTER => MASTER_VALUE);
-- ERR_KEY := TO_CHAR(LOCALTIMESTAMP,'YYYYMMDDHH24MISSFF6');
-- FOR AIX IN 1..LIST_PARAM(SOURCE_PROC).COUNT LOOP
-- INSERT INTO ERROR_LOG (ERR_KEY, ERR_SITE,ERR_SLAVE ,ERR_MASTER ,ERR_TYPE ,ERR_PROC,ERR_DATE,ERR_TXT)
-- VALUES (ERR_KEY,SITE,REF_VALUE,MASTER_VALUE,'LOG',SOURCE_PROC,LIST_PARAM(SOURCE_PROC)(AIX).ERR_DATE ,LIST_PARAM(SOURCE_PROC)(AIX).ERR_TXT);
-- END LOOP;
-- UPDATE SESSION_CONTEXT SET SCX_ERR_KEY = ERR_KEY WHERE SCX_ID = SYS_CONTEXT('USERENV','SESSIONID');
-- LIST_PARAM.DELETE(SOURCE_PROC);
-- COMMIT;
EXCEPTION
WHEN OTHERS THEN
LIST_PARAM.DELETE(SOURCE_PROC);
END LOGS;
PROCEDURE ERRORS(REF_TYPE IN VARCHAR2 DEFAULT 'SITE', REF_VALUE IN VARCHAR2 DEFAULT '99', ERR_CODE IN NUMBER DEFAULT SQLCODE, ERR_MSG IN VARCHAR2 DEFAULT SQLERRM)
AS
PRAGMA AUTONOMOUS_TRANSACTION;
MASTER_VALUE ERROR_LOG.ERR_MASTER%TYPE;
SITE PARAMTAB.SITE_CODE%TYPE;
SOURCE_OWNER all_source.OWNER%TYPE;
SOURCE_NAME all_source.NAME%TYPE;
SOURCE_LINE all_source.LINE%TYPE;
SOURCE_TEXT all_source.TEXT%TYPE;
SOURCE_PROC VARCHAR2(4000);
ERR_KEY NUMBER := TO_CHAR(LOCALTIMESTAMP,'YYYYMMDDHH24MISSFF6');
BEGIN
OWA_UTIL.WHO_CALLED_ME(owner => SOURCE_OWNER,
name => SOURCE_NAME,
lineno => SOURCE_LINE,
caller_t => SOURCE_TEXT);
SOURCE_PROC := SUBSTR(GET_PROC_NAME(SOURCE_OWNER,SOURCE_NAME,SOURCE_LINE),1,125);
SELECT_MASTER(REF_TYPE => UPPER(REF_TYPE), PARAM_VALUE => REF_VALUE, SITE => SITE, REF_MASTER => MASTER_VALUE);
IF LIST_PARAM.EXISTS(SOURCE_PROC) THEN
FOR AIX IN 1..LIST_PARAM(SOURCE_PROC).COUNT LOOP
INSERT INTO ERROR_LOG (ERR_KEY,ERR_SITE,ERR_SLAVE,ERR_MASTER,ERR_PROC,ERR_DATE,ERR_TXT,ERR_CODE,ERR_MSG)
VALUES (ERR_KEY,SITE,REF_VALUE,MASTER_VALUE,SOURCE_PROC,LIST_PARAM(SOURCE_PROC)(AIX).ERR_DATE, LIST_PARAM(SOURCE_PROC)(AIX).ERR_TXT,ERR_CODE,ERR_MSG);
END LOOP;
LIST_PARAM.DELETE(SOURCE_PROC);
ELSE
INSERT INTO ERROR_LOG (ERR_KEY,ERR_SITE,ERR_SLAVE,ERR_MASTER,ERR_PROC,ERR_DATE,ERR_TXT,ERR_CODE,ERR_MSG)
VALUES (ERR_KEY,SITE,REF_VALUE,MASTER_VALUE,SOURCE_PROC,CURRENT_TIMESTAMP,'Error info',ERR_CODE,ERR_MSG);
END IF;
UPDATE SESSION_CONTEXT SET SCX_ERR_KEY = ERR_KEY WHERE SCX_ID = sys_context('usr_context', 'session_id');
COMMIT;
EXCEPTION
WHEN OTHERS THEN
LIST_PARAM.DELETE(SOURCE_PROC);
END ERRORS;
END PAC_LOG_ERROR;This package is always call. On each routines performed I execute it. In the trace log of the database we have see a problem we the procedure GET_PROC_NAME in the package. We have identify that is called more that 800x and increase the performance. Who increase is this select command :
SELECT * INTO SOURCE_TEXT
FROM (SELECT TEXT FROM all_source
WHERE OWNER = SOURCE_OWNER AND
NAME=SOURCE_NAME AND
TYPE IN ('PROCEDURE','FUNCTION','PACKAGE BODY') AND
LINE <= SOURCE_LINE AND SUBSTR(TRIM(TEXT),1,9) IN ('PROCEDURE','FUNCTION ')
ORDER BY LINE DESC)
WHERE ROWNUM = 1;Complex SQL like inline views and views of views can overwhelm the cost-based optimizer resulting in bad execution plans. Start with getting an execution plan of your problem query to see if it is inefficient - look for full table scans in particular. You might bet better performance by eliminating the IN and merging the results of 3 queries with a UNION. -
How to ZIP file and send via SMTP in Oracle
Dear All,
I want to send data every month via email where the data i got from view.
The problem is the file is to big, so i should zip it.
the question is How i can perform it with procedure and send it automatically via Job every 1st month
what i've done was i create a procedure to make the file in zip
[quote/]
CREATE OR REPLACE PROCEDURE production.CREATE_EXCEL_DTKPITerminate IS
vvrun varchar2(3000);
vsender varchar2(100);
vrecepient varchar2(100);
vccrecipient varchar2(1000);
vsubject varchar2(1000);
vmessage long;
v_loc varchar2(5);
NAME: CREATE_EXCEL
PURPOSE:
REVISIONS:
Ver Date Author Description
1.0 10/15/2012 1. Created this procedure.
NOTES:
Automatically available Auto Replace Keywords:
Object Name: CREATE_EXCEL
Sysdate: 10/15/2012
Date and Time: 10/15/2012, 9:42:40 , and 10/15/2012 9:42:40
Username: (set in TOAD Options, Procedure Editor)
Table Name: (set in the "New PL/SQL Object" dialog)
begin
vsender := '[email protected]';
vrecepient := '[email protected]';
vccrecipient := '[email protected]';
vsubject := 'KPI Terminate'||TO_CHAR(SYSDATE,'MM-YYYY');
vmessage :=
'MESSAGE .';
as_xlsx.query2sheet('
select cmp_company,emp#,name,class,goucode,goudesc,job,job_name,tglkeluar
,nac_seq,nac_code,nac_type,nac_begin,nac_desc,reason,reason_code
from V_KPITerminate
--insert into blobs(blob_id,blob_name)
--values (1,as_xlsx.finish);
SEND_SMTP_PUZZLE_DTKRY(vsender,vrecepient,vccrecipient,vsubject,vmessage,as_xlsx.finish,'DataKPITerm -'||to_char(sysdate,'yyyy')||'.zip');
--as_xlsx.save( 'BASE_DIR3', 'SWT.xls' );
end;
[/quote]
when i execute this, Error ocured
Message : ORA-29278: SMTP transient error: 421 Service not available
ORA-06512 : at "SYS.UTL_SMTP", line 21
ORA-06512 : at "SYS.UTL_SMTP", line 97
ORA-06512 : at "SYS.UTL_SMTP", line 399
ORA-06512 : at "PU22PROD_123.SEND_SMTP_PUZZLE_DTKRY", line 151
ORA-29294 : A data error occurred during compression or uncompression.
ORA-06512 : at "PU22PROD_123.CREATE_EXCEL_KPITERM", line 60
ORA-06512 : at line 2
cann anyone help?
the data is too big so i prefer it zip.. can anyone help..
the SMTP I use is like this
CREATE OR REPLACE PROCEDURE production.SEND_SMTP_PUZZLE_DTKRY (pSender VARCHAR2,pRecipient VARCHAR2, pCCRecipient VARCHAR2, pSubject VARCHAR2,pMessage LONG,pattach BLOB,pfilename VARCHAR2) IS
v_src_loc BFILE := BFILENAME('BASE_DIR3', 'pajak.xls');
l_buffer RAW(54);
l_amount BINARY_INTEGER := 54;
l_pos INTEGER := 1;
l_blob BLOB := EMPTY_BLOB;
l_blob_len INTEGER;
v_amount INTEGER;
crlf CONSTANT VARCHAR2(2):= CHR(13) || CHR(10);
v_connection_handle UTL_SMTP.CONNECTION;
v_smtp_host VARCHAR2(30) := 'mail.mayora.co.id'; --My mail server, replace it with yours.
v_subject VARCHAR2(30) := 'Your Test Mail';
l_message VARCHAR2(200) := 'This is test mail using UTL_SMTP';
pcc varchar2(50);
i number := 1;
j number := 1;
l_original_blob blob;
l_compressed_blob blob;
BEGIN
BEGIN
/*Preparing the LOB from file for attachment. */
--DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY); --Read the file
--dBMS_LOB.CREATETEMPORARY(l_blob, TRUE); --Create temporary LOB to store the file.
--v_amount := DBMS_LOB.GETLENGTH(v_src_loc); --Amount to store.
--DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount); -- Loading from file into temporary LOB
--l_blob_len := DBMS_LOB.getlength(l_blob);
l_original_blob := pattach;
l_compressed_blob := TO_BLOB('1');
UTL_COMPRESS.lz_compress (src => l_original_blob,
dst => l_compressed_blob);
--DBMS_LOB.FREETEMPORARY(l_compressed_blob);
l_blob := l_compressed_blob;
l_blob_len := DBMS_LOB.getlength(l_blob);
/*UTL_SMTP related coding. */
v_connection_handle := UTL_SMTP.OPEN_CONNECTION(host => v_smtp_host);
UTL_SMTP.HELO(v_connection_handle, v_smtp_host);
UTL_SMTP.MAIL(v_connection_handle, psender);
UTL_SMTP.RCPT(v_connection_handle, precipient);
if pCCRecipient is not null then
if(instr(pCCRecipient,',') = 0) then
utl_smtp.rcpt(v_connection_handle, pCCRecipient);
else
while(instr(pCCRecipient,',',i) > 0)
loop
pcc := substr(pCCRecipient,i, instr(substr(pCCRecipient,i),',')-1);
i := i+instr(substr(pCCRecipient,i),',');
utl_smtp.rcpt(v_connection_handle,pcc);
end loop;
pcc := substr(pCCRecipient,i,length(pCCRecipient));
utl_smtp.rcpt(v_connection_handle,pcc);
end if;
end if;
--UTL_SMTP.RCPT(v_connection_handle, v_cc_email_address);
UTL_SMTP.OPEN_DATA(v_connection_handle);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'FROM' || ': ' || psender || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'TO' || ': ' || precipient || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'CC' || ': ' || pCCRecipient || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'SUBJECT' || ': ' || pSubject || UTL_TCP.CRLF);
--MIME header.
UTL_SMTP.WRITE_DATA(v_connection_handle,
'MIME-Version: 1.0' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Type: multipart/mixed; ' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
' boundary= "' || 'BASE_DIR3.SECBOUND' || '"' ||
UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
-- Mail Body
UTL_SMTP.WRITE_DATA(v_connection_handle,
'--' || 'BASE_DIR3.SECBOUND' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Type: text/plain;' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
' charset=US-ASCII' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, Pmessage || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
-- Mail Attachment
UTL_SMTP.WRITE_DATA(v_connection_handle,
'--' || 'BASE_DIR3.SECBOUND' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Type: application/octet-stream' ||
UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Disposition: attachment; ' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
' filename="' || pfilename || '"' || --My filename
UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Transfer-Encoding: base64' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
/* Writing the BLOL in chunks */
WHILE l_pos < l_blob_len LOOP
DBMS_LOB.READ(l_blob, l_amount, l_pos, l_buffer);
UTL_SMTP.write_raw_data(v_connection_handle,
UTL_ENCODE.BASE64_ENCODE(l_buffer));
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
l_buffer := NULL;
l_pos := l_pos + l_amount;
END LOOP;
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
-- Close Email
UTL_SMTP.WRITE_DATA(v_connection_handle,
'--' || 'BASE_DIR3.SECBOUND' || '--' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
UTL_TCP.CRLF || '.' || UTL_TCP.CRLF);
UTL_SMTP.CLOSE_DATA(v_connection_handle);
UTL_SMTP.QUIT(v_connection_handle);
EXCEPTION
WHEN OTHERS THEN NULL;
--return 1;
UTL_SMTP.QUIT(v_connection_handle);
RAISE;
END;
END;this is my smtp procedure
CREATE OR REPLACE PROCEDURE PROD.SEND_SMTP_PUZZLE_DTKRY (pSender VARCHAR2,pRecipient VARCHAR2, pCCRecipient VARCHAR2, pSubject VARCHAR2,pMessage LONG,pattach BLOB,pfilename VARCHAR2) IS
v_src_loc BFILE := BFILENAME('BASE_DIR3', 'pajak.xls');
l_buffer RAW(54);
l_amount BINARY_INTEGER := 54;
l_pos INTEGER := 1;
l_blob BLOB := EMPTY_BLOB;
l_blob_len INTEGER;
v_amount INTEGER;
crlf CONSTANT VARCHAR2(2):= CHR(13) || CHR(10);
v_connection_handle UTL_SMTP.CONNECTION;
v_smtp_host VARCHAR2(30) := 'mail.mayora.co.id'; --My mail server, replace it with yours.
v_subject VARCHAR2(30) := 'Your Test Mail';
l_message VARCHAR2(200) := 'This is test mail using UTL_SMTP';
pcc varchar2(50);
i number := 1;
j number := 1;
l_original_blob blob;
l_compressed_blob blob;
BEGIN
BEGIN
/*Preparing the LOB from file for attachment. */
--DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY); --Read the file
--dBMS_LOB.CREATETEMPORARY(l_blob, TRUE); --Create temporary LOB to store the file.
--v_amount := DBMS_LOB.GETLENGTH(v_src_loc); --Amount to store.
--DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount); -- Loading from file into temporary LOB
--l_blob_len := DBMS_LOB.getlength(l_blob);
l_original_blob := pattach;
l_compressed_blob := TO_BLOB('1');
UTL_COMPRESS.lz_compress (src => l_original_blob,
dst => l_compressed_blob);
--DBMS_LOB.FREETEMPORARY(l_compressed_blob);
l_blob := l_compressed_blob;
l_blob_len := DBMS_LOB.getlength(l_blob);
/*UTL_SMTP related coding. */
v_connection_handle := UTL_SMTP.OPEN_CONNECTION(host => v_smtp_host);
UTL_SMTP.HELO(v_connection_handle, v_smtp_host);
UTL_SMTP.MAIL(v_connection_handle, psender);
UTL_SMTP.RCPT(v_connection_handle, precipient);
if pCCRecipient is not null then
if(instr(pCCRecipient,',') = 0) then
utl_smtp.rcpt(v_connection_handle, pCCRecipient);
else
while(instr(pCCRecipient,',',i) > 0)
loop
pcc := substr(pCCRecipient,i, instr(substr(pCCRecipient,i),',')-1);
i := i+instr(substr(pCCRecipient,i),',');
utl_smtp.rcpt(v_connection_handle,pcc);
end loop;
pcc := substr(pCCRecipient,i,length(pCCRecipient));
utl_smtp.rcpt(v_connection_handle,pcc);
end if;
end if;
--UTL_SMTP.RCPT(v_connection_handle, v_cc_email_address);
UTL_SMTP.OPEN_DATA(v_connection_handle);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'FROM' || ': ' || psender || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'TO' || ': ' || precipient || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'CC' || ': ' || pCCRecipient || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'SUBJECT' || ': ' || pSubject || UTL_TCP.CRLF);
--MIME header.
UTL_SMTP.WRITE_DATA(v_connection_handle,
'MIME-Version: 1.0' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Type: multipart/mixed; ' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
' boundary= "' || 'BASE_DIR3.SECBOUND' || '"' ||
UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
-- Mail Body
UTL_SMTP.WRITE_DATA(v_connection_handle,
'--' || 'BASE_DIR3.SECBOUND' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Type: text/plain;' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
' charset=US-ASCII' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, Pmessage || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
-- Mail Attachment
UTL_SMTP.WRITE_DATA(v_connection_handle,
'--' || 'BASE_DIR3.SECBOUND' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Type: application/octet-stream' ||
UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Disposition: attachment; ' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
' filename="' || pfilename || '"' || --My filename
UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
'Content-Transfer-Encoding: base64' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
/* Writing the BLOL in chunks */
WHILE l_pos < l_blob_len LOOP
DBMS_LOB.READ(l_blob, l_amount, l_pos, l_buffer);
UTL_SMTP.write_raw_data(v_connection_handle,
UTL_ENCODE.BASE64_ENCODE(l_buffer));
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
l_buffer := NULL;
l_pos := l_pos + l_amount;
END LOOP;
UTL_SMTP.WRITE_DATA(v_connection_handle, UTL_TCP.CRLF);
-- Close Email
UTL_SMTP.WRITE_DATA(v_connection_handle,
'--' || 'BASE_DIR3.SECBOUND' || '--' || UTL_TCP.CRLF);
UTL_SMTP.WRITE_DATA(v_connection_handle,
UTL_TCP.CRLF || '.' || UTL_TCP.CRLF);
UTL_SMTP.CLOSE_DATA(v_connection_handle);
UTL_SMTP.QUIT(v_connection_handle);
EXCEPTION
WHEN OTHERS THEN NULL;
--return 1;
UTL_SMTP.QUIT(v_connection_handle);
RAISE;
END;
END;
is there a mistake? -
Need help with create trigger based on more then 1 table and join.
Hello,
Here i have 3 tables
1. Employee
PERSON_ID
1
1
N
NUMBER
None
ORG_ID
2
N
NUMBER
Frequency
LOC_ID
3
N
NUMBER
Frequency
JOB_ID
4
Y
NUMBER
Height Balanced
FLSA_STATUS_ID
5
Y
NUMBER
Frequency
FULL_NAME
6
N
VARCHAR2 (250 Byte)
Height Balanced
FIRST_NAME
7
N
VARCHAR2 (20 Byte)
Height Balanced
MIDDLE_NAME
8
Y
VARCHAR2 (60 Byte)
Height Balanced
LAST_NAME
9
N
VARCHAR2 (40 Byte)
Height Balanced
PREFERRED_NAME
10
Y
VARCHAR2 (80 Byte)
None
EMAIL
11
Y
VARCHAR2 (250 Byte)
None
MAILSTOP
12
Y
VARCHAR2 (100 Byte)
None
HIRE_DATE
13
N
DATE
None
2. ems_candidate
EMS_CANDIDATE_ID
1
1
N
NUMBER
None
EMS_JOB_ID
2
Y
NUMBER
Frequency
NAME
3
N
VARCHAR2 (255 Byte)
Frequency
EMAIL
4
Y
VARCHAR2 (255 Byte)
None
TELEPHONE
5
Y
VARCHAR2 (25 Byte)
None
EMS_SOURCE_ID
6
Y
NUMBER
Frequency
RECEIVED_DATE
7
Y
DATE
Frequency
COMMENTS
8
Y
VARCHAR2 (4000 Byte)
None
3. employee_resources
EMP_RES_ID
1
1
N
NUMBER
None
PERSON_ID
2
Y
NUMBER
Height Balanced
CANDIDATE_ID
3
Y
NUMBER
Frequency
EMP_START_DATE
4
Y
DATE
None
CUSTOM_RESOURCE_FLAG
5
Y
NUMBER (1)
None
RESOURCE_GROUP_ID
6
N
NUMBER
Frequency
RESOURCE_STATUS_ID
7
N
NUMBER
Frequency
GROUP_LOC_ID
8
N
NUMBER
Height Balanced
ASSIGNED_JIRA
9
Y
VARCHAR2 (250 Byte)
None
REVOKED_JIRA
10
Y
VARCHAR2 (250 Byte)
None
CREATED_DATE
11
Y
DATE
SYSDATE
None
UPDATED_DATE
12
Y
DATE
None
Now i want to create trigger when new record get inserted in employee table wanted to update person_id in employee_resources table.
So i want to match ems_candidate.name with employee.full_name , ems_candidate.ems_job_id with employee.ems_job_id. And if it matched then update person_id in employee_resources table else through an exception and insert record in temp table.
If anybody has an idea can u please help me.
Thanks,
Gayatri.I created below trigger
CREATE TRIGGER emp_resources_upd_person_id
AFTER INSERT ON ems.employee
FOR EACH ROW
BEGIN
UPDATE ems.employee_resources
SET person_id = :new.person_id
WHERE candidate_id = (SELECT ems_candidate_id
FROM ems.ems_candidate cand, ems.employee emp
WHERE TRIM(UPPER(emp.first_name)) = TRIM(UPPER(SUBSTR (cand.name, 1, INSTR (cand.name, ' ') - 1)))
AND TRIM(UPPER(emp.last_name)) = TRIM(UPPER(SUBSTR (cand.name,INSTR (cand.name, ' ') + 1,DECODE (INSTR (SUBSTR (cand.name, INSTR (cand.name, ' ') + 1), ' '),0,LENGTH (cand.name),(INSTR (SUBSTR (cand.name, INSTR (cand.name, ' ') + 1), ' ') - 1)))))
AND emp.person_id = :new.person_id);
EXCEPTION
WHEN OTHERS THEN
INSERT INTO ems.update_person_id_exception(person_id,first_name,last_name,full_name) VALUES(:new.person_id,:new.first_name,:new.last_name,:new.full_name);
END;
Now when i am trying to insert row in ems.employee table it gives me an error
ORA-04091
table string.string is mutating, trigger/function may not see it
Cause: A trigger (or a user defined plsql function that is referenced in this statement) attempted to look at (or modify) a table that was in the middle of being modified by the statement which fired it.
Action: Rewrite the trigger (or function) so it does not read that table.
Can anybody please help me to come out from these error.
Thanks,
Gayatri. -
Any Function which can solve my problem.
Hi all
I am working on Character based report from which i use to take print on my check using dot matrix printer.
my query is
1) when i want to type my amount in words there may be chances of overlapping my amount in words with other field because may be the value is too large.
for e.g here in front of rupee that much character be fix other may go to other line.
PAY............................................................
RUPEES....................................................... RS.2206
i have tried
SELECT SUBSTR('Two Thousand Two Hundred Six only',1,25) FROM DUAL
SELECT SUBSTR('Two Thousand Two Hundred Six only',25,100) FROM DUAL
but some time the value get changed then like 3206
then
if we will use same in report
SELECT SUBSTR('Three Thousand Two Hundred Six only',1,25) FROM DUAL
SELECT SUBSTR('Three Thousand Two Hundred Six only',25,100) FROM DUAL
PAY............................................................
RUPEES.Three Thousand Two Hundre. RS.2206
ed Six only.
run time in report.it should not come like this.
is there any function or solution for this.assuming your max length is 25, this sql will split the string at the last blank:
WITH t As (
SELECT 'Three Thousand Two Hundreed Six only.' text FROM dual UNION
SELECT 'Two Hundreed Six only.' FROM dual UNION
SELECT 'Three Thousand Three Hundreed Three only.' FROM dual
SELECT
SUBSTR(text, 1, INSTR(SUBSTR(text, 1, 25), ' ', -1) - 1) row1,
SUBSTR(text, INSTR(SUBSTR(text, 1, 25), ' ', -1) + 1) row2
FROM t;
ROW1
ROW2
Three Thousand Three
Hundreed Three only.
Three Thousand Two
Hundreed Six only.
Two Hundreed Six
only. -
How to get the name before @ in an email id
Hi All,
How can i get the name before '@' in an email id, for example if i have [email protected], how do i get 'abc' in my query result.
Thanksthinkingeye wrote:
Hi All,
How can i get the name before '@' in an email id, for example if i have [email protected], how do i get 'abc' in my query result.
Thankscombine INSTR() & SUBSTR() functions
Maybe you are looking for
-
Error in Purchasing Document Open Interface POXPOPDOI
Dear Gurus, I am trying to uplod Complex Purchase Orders in Oracle EBS R 12.1.2 The PO_INTERFACE_ERRORS table is populated with the following message: STYLE_ID Error: Style (STYLE_ID = 103) with progress payments is not supported. We have checked
-
I am trying to reset my pass word for my Parent Control. I just renewed my internet security and the security keeps me from going to site even though I am the adminstrator.
-
Firing plug shows wite content area
Hello everybody! Currently we encounter a strange problem in one of our WebDynpro applications. When a certain user clicks on a button that fires a plug to navigate to another view, the contet area gets white and nothing else happens. This happens to
-
Is anyone having a problem with the power plugs?
My power plugs are getting shorts to where they will not charge up the laptop any longer. I had this laptop 2 years and been through 3 cords already. Sometimes they get really hot too
-
What user exit to use in F110?
Hi everyone! In F110, I need to check if Posting Date used is equal to Run Date. What user exit should I use to write this logic? Thank you!