Replace function in sql
Hi Gurus,
select replace(',"hel,lo1","' , ',' , ':') from dual
It is getting replaced as :"hel:lo1":"
but i want to get replaced as :"hel,lo1":"
Could anyone suggest me a solution to solve this problem..
Thanks in advance
kavitha L
Like this?
ME_XE?select replace(',"hel,lo1","' , ',"', ':"') from dual;
REPLACE(',"HEL,LO1","',',"',':"')
:"hel,lo1":"
1 row selected.
Elapsed: 00:00:06.07
{code}
Similar Messages
-
Replace Values for a Col under a Table using Replace Function in Sql Query
Hi all
I have a Custom Table by Name RESP_TABLE which stores the Responsibility Names under the Column RESPONSIBILITY.
The Sample Value for this col is as follows :
PF <CNTRY> Gl Analyst <CCY>.
This <CNTRY> Stands for Country Short Name
and <CCY> Stands for Currency.
The <CNTRY> & <CCY> should be passed as a parameter at the run time.
Based on the value given at the run time it should change accordingly.
For example
PF <CNTRY> Gl Analyst <CCY>
<CNTRY> Value passed at runtime : BE
<CCY> Value passed at runtime : CAD
So the resulting value should be as follows :
PF BE Gl Analyst CAD.
I had already used the query given below :
SELECT REPLACE(RESPONSIBILITY,'<CNTRY>','&MARKET') FROM RESP_TABLE.
This works fine for Country Code alone but not for currency.
I need both the Country Code and Currency Code to be changed to the respective values given at the runtime.
Could anybody please help me on this ?
Regards
Nakul Venkataraman.Hi Nakul,
Why not just adding another REPLACE to what you still have achieved? :)
Regards,
Guido -
Creating Functions in SQL server
HI
i creating functions for specific purpose in the test database...
is it against SAP Support policy?
suggest me...if you are just going to start entries then you can .
But i have posted then Use replace function in SQL
SQL Syntax:
REPLACE( string1, string2, string3 )
Parameters:
string1
Any character string or binary expression that can contain the string from string2.
string2
Any character string or binary expression. This string is searching in string1.
string3
Any character string or binary expression. This string replace all occurrence of string2.
May it will work
Thanks
Manvendra Singh Niranjan -
Error ORA-06502 When using function REPLACE in PL/SQL
Hi,
I have a PL/SQL procedure which gives error 'Error ORA-06502 When using function REPLACE in PL/SQL' when the string value is quite long (I noticed this with a string 9K in length)
variable var_a is of type CLOB
and the assignment statement where it gives the error is
var_a := REPLACE(var_a, '^', ''',''');
Can anyone please help!
ThanksEven then that shouldn't do so:
SQL> select overload, position, argument_name, data_type, in_out
2 from all_arguments
3 where package_name = 'STANDARD'
4 and object_name = 'LPAD'
5 order by 1,2
6 /
OVERLOAD POSITION ARGUMENT_NAME DATA_TYPE IN_OUT
1 0 VARCHAR2 OUT
1 1 STR1 VARCHAR2 IN
1 2 LEN BINARY_INTEGER IN
1 3 PAD VARCHAR2 IN
2 0 VARCHAR2 OUT
2 1 STR1 VARCHAR2 IN
2 2 LEN BINARY_INTEGER IN
3 0 CLOB OUT
3 1 STR1 CLOB IN
3 2 LEN NUMBER IN
3 3 PAD CLOB IN
4 0 CLOB OUT
4 1 STR1 CLOB IN
4 2 LEN NUMBER INI wonder what happened? -
SQL replace function in JDeveloper
In SQL*Plus I run the following queries...
select last_name, phone_number from employees
LAST_NAME PHONE_NUMBER
Chung 650.505.1876
Dilly 650.505.2876
Gates 916.764.6600
select last_name, replace (phone_number, '.', '-') from employees
LAST_NAME REPLACE(PHONE_NUMBER
Chung 650-505-1876
Dilly 650-505-2876
Gates 916-764-6600
If I try to use the "REPLACE" function in the JDeveloper by editing the sql statement in the view object editor and run the page the results returned for the phone number column on the page are blank.
How can I substitute a dash for the period on the page?Try using AS:
select last_name, replace (phone_number, '.', '-') AS phone_number from employees
In this case is recommended for your VO a read only query. -
SQL Replace function: errors if replacement text is 8191 characters
Oracle 10.2.0.3.0 Enterprise Edition
I'm working on an application which has a function to generate emails.
We have a template, which gets filled with data from the database depending on the email being sent.
To do this I'm using the Replace function to replace certain parts of the template with the right data.
It seems that if the replacement text (the third argument to the function) is longer than 8191 bytes the function throws a PL/SQL: numeric or value error.
This limitation doesn't appear to be documented anywhere, certainly nowhere that I can find.
Anyone know of a way around this short of building my own replace function?I've figured out what was going on.
The database column for the replacement text is defined as a clob, but there is a front end limit of 10,000 characters for the field being used.
When using the replace function I was assigning the value to a varchar2(32767) field in the PL/SQL.
So in terms of datatypes the function call is:
varchar2 := replace(varchar2, varchar2, clob)
If the length of the clob is over 8191 characters it errors.
(Presumably because of the bug mentioned in this thread DBMS_LOB.SUBSTR() returning 8191 characters instead of 32767
I've fixed it by simply changing the datatype of the variable to which the value is being assigned to a clob. -
Want to convert function in SQL Server 2000
Hi ,
i am writing this function in oracle.Could you please convert this function in SQL Server 2000 because i am new in this and dont know how to use decode function in sql.
Please following is the code for oracle.
CREATE OR REPLACE function fun ( localex varchar2,titlex varchar2)
return number
as x number;
begin
select sum ( decode (count (username),max(prereq_count),1,0) ) x into x from
SELECT
prereq_count,
username
FROM
table1
group by username ;
return x;
end fun;
Regards
VishalJust take a look example below might give you idea :
create or replace function f_makeAddress_tx (
i_address_tx VARCHAR2,
i_city_tx VARCHAR2,
i_state_tx VARCHAR2,
i_zip_tx VARCHAR2)
return VARCHAR2
is
e_badZip EXCEPTION; u279E8
pragma EXCEPTION_init(e_badZip,-20998); u279E9
v_out_tx VARCHAR2(256);
begin
p_validateZip (i_zip_tx); u279E12
v_out_tx:= i_address_tx||u2019, u2018|| u279E13
i_city_tx ||u2019, u2018||
i_state_tx ||u2019, u2018||
i_zip_tx;
return v_out_tx; u279E17
exception
when e_badZip then u279E19
return i_zip_tx || u2018: Invalid zip code.u2019;
end;
Regards,
Clint -
Using User Defined Function is SQL
Hi
I did the following test to see how expensive it is to use user defined functions in SQL queries, and found that it is really expensive.
Calling SQRT in SQL costs less than calling a dummy function that just returns
the parameter value; this has to do with context switchings, but how can we have
a decent performance compared to Oracle provided functions?
Any comments are welcome, specially regarding the performance of UDF in sql
and for solutions.
create or replace function f(i in number) return number is
begin
return i;
end;
declare
l_start number;
l_elapsed number;
n number;
begin
select to_char(sysdate, 'sssssss')
into l_start
from dual;
for i in 1 .. 20 loop
select max(rownum)
into n
from t_tdz12_a0090;
end loop;
select to_char(sysdate, 'sssssss') - l_start
into l_elapsed
from dual;
dbms_output.put_line('first: '||l_elapsed);
select to_char(sysdate, 'sssssss')
into l_start
from dual;
for i in 1 .. 20 loop
select max(sqrt(rownum))
into n
from t_tdz12_a0090;
end loop;
select to_char(sysdate, 'sssssss') - l_start
into l_elapsed
from dual;
dbms_output.put_line('second: '||l_elapsed);
select to_char(sysdate, 'sssssss')
into l_start
from dual;
for i in 1 .. 20 loop
select max(f(rownum))
into n
from t_tdz12_a0090;
end loop;
select to_char(sysdate, 'sssssss') - l_start
into l_elapsed
from dual;
dbms_output.put_line('third: '||l_elapsed);
end;
Results:
first: 303
second: 1051
third: 1515
Kind regards
TaoufikI find that inline SQL is bad for performance but
good to simplify SQL. I keep thinking that it should
be possible somehow to use a function to improve
performance but have never seen that happen.inline SQL is only bad for performance if the database design (table structure, indexes etc.) is poor or the way the SQL is written is poor.
Context switching between SQL and PL/SQL for a User defined function is definitely a way to slow down performance.
Obviously built-in Oracle functions are going to be quicker than User-defined functions because they are written into the SQL and PL/SQL engines and are optimized for the internals of those engines.
There are a few things you can do to improve function
performance, shaving microseconds off execution time.
Consider using the NOCOPY hints for your parameters
to use pointers instead of copying values. NOCOPY
is a hint rather than a directive so it may or may
not work. Optimize any SQL in the called function.
Don't do anything in loops that does not have to be
done inside a loop.Well, yes, but it's even better to keep all processing in SQL where possible and only resort to PL/SQL when absolutely necessary.
The on-line documentation has suggested that using a
DETERMINISTIC function can improve performance but I
have not been able to demonstrate this and there are
notes in Metalink suggesting that this does not
happen. My experience is that DETERMINISTIC
functions always get executed. There's supposed to
be a feature in 11g that acually caches function
return values.Deterministic functions will work well if used in conjunction with a function based index. That can improve access times when querying data on the function results.
You can use DBMS_PROFILER to get run-time statistics
for each line of your function as it is executed to
help tune it.Or code it as SQL. ;) -
I use function in SQL statement. It is a dynamicaly build SQL, therefore I need overload functions. These funcs defined in package. The package has PRAGMA Restrict_References (.., WNDS). So all functions should be restricted to update database.
But Oracle returns an error:
Function NVL_ does not guarantee not to update database
This is my build SQL:
----- the execution string is: ---------------
Begin
INSERT INTO TEST_TBL_BS (MILL_ORDER, CLM1, CLM2, CLM3, NOTES, INIT_DATE )
VALUES (NV.NVL_(Arc_Utl.TEST_TBL_dltd.MILL_ORDER),
NV.NVL_(Arc_Utl.TEST_TBL_dltd.CLM1),
NV.NVL_(Arc_Utl.TEST_TBL_dltd.CLM2),
NV.NVL_(Arc_Utl.TEST_TBL_dltd.CLM3),
NV.NVL_(Arc_Utl.TEST_TBL_dltd.NOTES),
Arch.Init_Time );
End;
This is NV package:
PACKAGE NV IS
PRAGMA Restrict_References ( NV, WNDS );
NULL_date DATE := TO_DATE ('01/01/1001', 'mm/dd/yyyy');
NULL_numb NUMBER := 0;
NULL_str VARCHAR2 (10)
:= '?';
-- overloaded NULL_Val function returns NULL_<type> value (defined early)
-- depend on received variable type
FUNCTION NULL_Val ( val_in IN DATE )
RETURN DATE ;
FUNCTION NULL_Val ( val_in IN NUMBER )
RETURN NUMBER ;
FUNCTION NULL_Val ( val_in IN VARCHAR2 )
RETURN VARCHAR2 ;
-- PRAGMA Restrict_References ( NULL_Val, WNDS ); -- can be used in SQLs
-- these pretends to cover hole of the SYS.NVL that do not have posibility
-- to return default NULL value for every given type
FUNCTION NVL_ ( val_in IN DATE )
RETURN DATE ;
FUNCTION NVL_ ( val_in IN NUMBER )
RETURN NUMBER ;
FUNCTION NVL_ ( val_in IN VARCHAR2 )
RETURN VARCHAR2 ;
-- PRAGMA Restrict_References ( NVL_, WNDS ); -- can be used in SQLs
END NV;
CREATE OR REPLACE PACKAGE BODY NV AS
-- NULL_Val set of overloaded functions - returns appropriate NULL value
FUNCTION NULL_Val ( val_in IN DATE )
RETURN DATE IS
BEGIN RETURN NULL_date;
END NULL_Val; -- for date
FUNCTION NULL_Val ( val_in IN NUMBER )
RETURN NUMBER IS
BEGIN RETURN NULL_numb;
END NULL_Val; -- for NUMBER
FUNCTION NULL_Val ( val_in IN VARCHAR2 )
RETURN VARCHAR2 IS
BEGIN RETURN NULL_str;
END NULL_Val; -- for VARCHAR2
-- set NVL_ function to return default NULL value if received variable
-- is NULL or the received variable if it is not NULL
FUNCTION NVL_ ( val_in IN DATE )
RETURN DATE IS
BEGIN RETURN NVL( val_in, NULL_Val ( val_in )); END NVL_;
FUNCTION NVL_ ( val_in IN NUMBER )
RETURN NUMBER IS
BEGIN RETURN NVL( val_in, NULL_Val ( val_in )); END NVL_;
FUNCTION NVL_ ( val_in IN VARCHAR2 )
RETURN VARCHAR2 IS
BEGIN RETURN NVL( val_in, NULL_Val ( val_in )); END NVL_;
END NV;
Can anybody help : where is a problem and what I can do in my case?
I work in Oracle 7.3
Thank you,
AlexHi Alex,
I've found that on the RDBS docs:
If you specify DEFAULT instead of a function name, the pragma applies to all functions in the package spec or object type spec (including, in the latter case, the
system-defined constructor). You can still declare the pragma for individual functions. Such pragmas override the default pragma.
Try using that and let me know.
The docs says also that the declaration of the pragma for an overloaded function applies to the nearest one. You may also try to insert several declaration, one after every function declaration.
Bye Max -
Calling PL/SQL functions in SQL
Hi,
I had a question on the behaviour of PL/SQL function when they are embedded in SQL queries.
I have simple PL/SQl function:
function get_city_id
(vCUSTOMER_GROUP_ID IN NUMBER)
RETURN VARCHAR2 AS
vIDs VARCHAR2(1000);
begin
vIDs := '2,3';
RETURN vIDs;
end;
I use an SQL query call this PL SQL function;
select equipment_id from equipment where equipment_type_id in (get_city_id(0));
When I run this query I get this error:
ERROR at line 1:
ORA-01722: invalid number
I understand that the SQL compiler is complaining that get_city_id() function is not returning a number. but isn't the PL/SQL suppose to be replace with whatever string is returned from the function.
This brings me to the second question: How can we return multiple values from a function to the SQL query, when the function is called in a SQL query. In my above explame, can the get_city_id() function return more than one city id and if yes, the how?
Thanks for the help in advance
regards
AlankarHow can we return multiple values from a function to the SQL query,Have it return a collection, e.g.
CREATE OR REPLACE TYPE VARCHAR2_TT AS TABLE OF VARCHAR2(4000)
CREATE OR REPLACE FUNCTION test_collection
RETURN VARCHAR2_TT
AS
BEGIN
RETURN VARCHAR2_TT(1,2,3);
END;
SELECT *
FROM employees
WHERE emp_id IN
( SELECT column_value
FROM TABLE(test_collection) ); -
Calling a function in sql prompt
hi
i have created one function in pl/sql
lik following
create or replace function ff(a number) return number is
x number;
begin
select ann_pct_rate into x from naap30_appproducts where applicant_id = a;
return x;
end;
while i called this in sql prompt i got an error like this
SQL> select ff(200610000493001) from dual;
select ff(200610000493001) from dual
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
is it possible to do like this how?
please advice
thanks in advance
sivasankarHi Radha,
i am very sorry, mistake is min i have wrongly specified the datatype. thanks for remind me. now it is ok
i have corrected the table like this
create or replace function ff(a number) return varchar2 is
x varchar2(50);
begin
select ann_pct_rate into x from appproducts where applicant_id = a;
return x;
end;
out put is
select ff(200610000493001) from dual;
FF(200610000493001)
18.5000%
thanks
sivasankar -
Replace() function doesn't work in Application Designer?
I'm using PeopleSoft Application Designer 8.51. I'm trying to do a simple Replace function so I can escape single quotes rather than allow them to blow up the sql query.
&deptid = Replace(&deptid, "'", "''");
App Designer chokes when I hit Save: "Invalid function parameter type. (2,19)"
According to the docs I'm using this correctly: http://docs.oracle.com/cd/E26239_01/pt851h3/eng/psbooks/tace/book.htm?File=tace/htm/tace14.htm#H4095
Even if I try to execute the example right out of the documentation, I get the same error: REPLACE("StringFun", "Fun", "Number");
Is this a bug in app designer? REPLACE is a super common thing, it's not something obscure. How can this not work?
Thanks in advance.I figured this out. “Replace” is a strange duck function that relies on offsets. “Substitute” is the magic I needed, works just like I was expecting Replace to work. The documentation I was reading on Replace was for “ PeopleSoft Analytic Calculation Engine” rather than peoplecode. I’ll pay closer attention to that next time. Maybe this will help someone else...
-
Using UTL_HTTP.GET_RESPONSE function (PL/SQL)
Hello,
I have a problem using the UTL_HTTP.GET_RESPONSE (URL, 'POST') function while I try to call a function that returns an XML;
The function returning my XML is:
FUNCTION MyFunction return XMLTYPE is
begin
return XMLTYPE('<PROVA>test</PROVA>');
end MyFunction;
To perform the http call I use this function:
FUNCTION POST(URL VARCHAR2, DATA_IN CLOB) RETURN CLOB IS
BEGIN
DECLARE
DATA_OUT CLOB;
PIECE VARCHAR2(4000);
AMT PLS_INTEGER := 4000;
POS PLS_INTEGER := 1;
HTTP_REQ UTL_HTTP.REQ;
HTTP_RESP UTL_HTTP.RESP;
BEGIN
HTTP_REQ := UTL_HTTP.BEGIN_REQUEST (URL, 'POST');
UTL_HTTP.SET_HEADER(HTTP_REQ, 'content-length', LENGTH(DATA_IN));
LOOP
DBMS_LOB.READ(DATA_IN,AMT,POS,PIECE);
UTL_HTTP.WRITE_TEXT(HTTP_REQ, PIECE);
EXIT WHEN AMT < 4000;
POS := POS + AMT;
AMT := 4000;
END LOOP;
HTTP_RESP := UTL_HTTP.GET_RESPONSE (HTTP_REQ);
BEGIN
LOOP
UTL_HTTP.READ_TEXT(HTTP_RESP, PIECE);
DATA_OUT := DATA_OUT || PIECE;
END LOOP;
EXCEPTION WHEN UTL_HTTP.END_OF_BODY THEN NULL;
END;
UTL_HTTP.END_RESPONSE (HTTP_RESP);
RETURN DATA_OUT;
END;
END;
The script pl/sql that calls the preceding function is:
declare
v_resp CLOB;
v_url VARCHAR2(4000);
begin
v_url := 'http:// ... /meters.export_table.MyFunction'
v_resp := POST(v_url, '-');
end;
After this call to my url, the variabile v_resp contains the following error message:
"<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>400 Bad Request</TITLE>
</HEAD><BODY>
<H1>Bad Request</H1>
Your browser sent a request that this server could not understand.<P>
mod_plsql: /pls/prjsi/meters.export_table.MyFunction HTTP-400 Missing '=' in query string or post form<P>
<HR>
<ADDRESS>Oracle-Application-Server-10g/10.1.2.0.2 Oracle-HTTP-Server Server at websvil.aem.torino.it Port 80</ADDRESS>
</BODY></HTML>"
Do you know how I can get my XML? What is the problem in that call http for my function?
ThanksHello !
I have not understand exactly what have you try to achieve with your code , but i thing there are few things misunderstood in your code ,
so i'm posting this very basic but working example in hope that it will help you
SQL>
SQL>
SQL> conn scott/tiger
Connected.
SQL>
SQL>
SQL> create or replace procedure http_test is
2 begin
3 htp.p('<PROVA>test</PROVA>');
4 end http_test;
5 /
Procedure created.
SQL> CREATE OR REPLACE function HTTP_POST return varchar2 is
2
3 req utl_http.req;
4 resp utl_http.resp;
5
6 v_txt varchar2(1024);
7
8 BEGIN
9
10 req := UTL_HTTP.begin_request ('http://localhost:7777/pls/my_utf8/http_test'
11 ,'POST','HTTP/1.1');
12 Utl_Http.Set_Authentication ( r => req, username => 'scott', password => 'tiger'
13 , scheme => 'Basic', for_proxy => false );
14 resp := UTL_HTTP.get_response (req);
15 utl_http.read_text(resp,v_txt);
16 utl_http.end_response(resp);
17 return v_txt;
18 END;
19 /
Function created.
SQL> select http_post from dual;
HTTP_POST
<PROVA>test</PROVA>
SQL> T -
Scaleability with Functions in SQL queries
Hi,
In one of our applications we have many views that use a packaged function in the where clause to filter data. This function uses a SYS_CONTEXT() to set and get values. There are couple of issues while using this approach:
1/ The deterministic function doesn't allow any scability with PQ-server.
2/ Another issue with this function and also the SYS_CONTEXT-function, they manuipulate the estimated CBO-statistics.
CREATE TABLE TAB_I
COLUMN1 NUMBER(16, 0) NOT NULL
, COLUMN2 VARCHAR2(20)
, CONSTRAINT TAB_I_PK PRIMARY KEY
COLUMN1
ENABLE
CREATE TABLE TAB_V
I_COL1 NUMBER(16,0) NOT NULL ENABLE,
VERSION_ID NUMBER(16,0) NOT NULL ENABLE,
CRE_DATIM TIMESTAMP (6) NOT NULL ENABLE,
TERM_DATIM TIMESTAMP (6) NOT NULL ENABLE,
VERSION_VALID_FROM DATE NOT NULL ENABLE,
VERSION_VALID_TILL DATE NOT NULL ENABLE,
CONSTRAINT TAB_V_PK PRIMARY KEY (I_COL1, VERSION_ID) USING INDEX NOCOMPRESS LOGGING ENABLE,
CONSTRAINT COL1_FK FOREIGN KEY (I_COL1) REFERENCES TAB_I (COLUMN1) ENABLE
CREATE OR REPLACE
PACKAGE app_bitemporal_rules IS
FUNCTION f_knowledge_time RETURN TIMESTAMP DETERMINISTIC;
END app_bitemporal_rules;
create or replace
PACKAGE BODY app_bitemporal_rules IS
FUNCTION f_knowledge_time RETURN TIMESTAMP DETERMINISTIC IS
BEGIN
RETURN TO_TIMESTAMP(SYS_CONTEXT ('APP_USR_CTX', 'KNOWLEDGE_TIME'),'DD.MM.YYYY HH24.MI.SSXFF');
END f_knowledge_time;
END app_bitemporal_rules;
explain plan for select *
FROM tab_i
JOIN tab_v
ON tab_i.column1 = tab_v.i_col1
AND app_bitemporal_rules.f_knowledge_time BETWEEN tab_v.CRE_DATIM AND tab_v.TERM_DATIM
where tab_i.column1 = 11111;
select * from table(dbms_xplan.display);
Plan hash value: 621902595
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 95 | 5 (0)| 00:00:06 |
| 1 | NESTED LOOPS | | 1 | 95 | 5 (0)| 00:00:06 |
| 2 | TABLE ACCESS BY INDEX ROWID| TAB_I | 1 | 25 | 1 (0)| 00:00:02 |
|* 3 | INDEX UNIQUE SCAN | TAB_I_PK | 1 | | 1 (0)| 00:00:02 |
|* 4 | TABLE ACCESS FULL | TAB_V | 1 | 70 | 4 (0)| 00:00:05 |
Predicate Information (identified by operation id):
3 - access("TAB_I"."COLUMN1"=11111)
4 - filter("TAB_V"."I_COL1"=11111 AND
"TAB_V"."CRE_DATIM"<="APP_BITEMPORAL_RULES"."F_KNOWLEDGE_TIME"() AND
"TAB_V"."TERM_DATIM">="APP_BITEMPORAL_RULES"."F_KNOWLEDGE_TIME"())
Note
- 'PLAN_TABLE' is old version
- dynamic sampling used for this statement (level=2)
explain plan for select *
FROM tab_i
JOIN tab_v
ON tab_i.column1 = tab_v.i_col1
AND '10-OCT-2011' BETWEEN tab_v.CRE_DATIM AND tab_v.TERM_DATIM
where tab_i.column1 = 11111;
select * from table(dbms_xplan.display);
Plan hash value: 621902595
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 256 | 24320 | 5 (0)| 00:00:06 |
| 1 | NESTED LOOPS | | 256 | 24320 | 5 (0)| 00:00:06 |
| 2 | TABLE ACCESS BY INDEX ROWID| TAB_I | 1 | 25 | 1 (0)| 00:00:02 |
|* 3 | INDEX UNIQUE SCAN | TAB_I_PK | 1 | | 1 (0)| 00:00:02 |
|* 4 | TABLE ACCESS FULL | TAB_V | 256 | 17920 | 4 (0)| 00:00:05 |
Predicate Information (identified by operation id):
3 - access("TAB_I"."COLUMN1"=11111)
4 - filter("TAB_V"."I_COL1"=11111 AND "TAB_V"."CRE_DATIM"<=TIMESTAMP'
2011-10-10 00:00:00.000000000' AND "TAB_V"."TERM_DATIM">=TIMESTAMP' 2011-10-10
00:00:00.000000000')
Note
- 'PLAN_TABLE' is old version
- dynamic sampling used for this statement (level=2) As can be seen in the second plan the cardinality has been guessed correctly, but not in the first case.
I have also tried with:
ASSOCIATE STATISTICS WITH packages app_bitemporal_rules DEFAULT COST (1000000/*246919*/,1000,0) DEFAULT SELECTIVITY 50;
But, this just leads to a increased cost, but no change in cardinality.
The (1) problem gets solved if I directly use "TO_TIMESTAMP(SYS_CONTEXT ('APP_USR_CTX', 'KNOWLEDGE_TIME'),'DD.MM.YYYY HH24.MI.SSXFF')" in the where clause. But am not able to find a solution for the (2) issue.
Can you please help.
Regards,
Vikram RHi Vikram,
On the subject of using [url http://download.oracle.com/docs/cd/E11882_01/server.112/e26088/statements_4006.htm#i2115932]ASSOCIATE STATISTICS, having done a little investigation on 11.2.0.2, I'm having trouble adjusting selectivity via "associate statististics ... default selectivity" but no problems with adjusting default cost.
I've also tried to do the same using an interface type and am running into other issues.
It's not functionality that I'm overly familiar with as I try to avoid/eliminate using functions in predicates.
Further analysis/investigation required.
Including test case of what I've done so far in case anyone else wants to chip in.
SQL> select * from v$version;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
PL/SQL Release 11.2.0.2.0 - Production
CORE 11.2.0.2.0 Production
TNS for Linux: Version 11.2.0.2.0 - Production
NLSRTL Version 11.2.0.2.0 - Production
SQL> drop table t1;
Table dropped.
SQL>
SQL> create table t1
2 as
3 select rownum col1
4 from dual
5 connect by rownum <= 100000;
Table created.
SQL>
SQL> exec dbms_stats.gather_table_stats(USER,'T1');
PL/SQL procedure successfully completed.
SQL>
SQL> create or replace function f1
2 return number
3 as
4 begin
5 return 1;
6 end;
7 /
Function created.
SQL>
SQL> create or replace function f2 (
2 i_col1 in number
3 )
4 return number
5 as
6 begin
7 return 1;
8 end;
9 /
Function created.
SQL> Created one table with 100000 rows.
Two functions - one without arguments, one with (for later).
With no associations:
SQL> select * from user_associations;
no rows selected
SQL> Run a statement that uses the function:
SQL> select count(*) from t1 where col1 >= f1;
COUNT(*)
100000
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID gm7ppkbzut114, child number 0
select count(*) from t1 where col1 >= f1
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 139 (100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 139 (62)| 00:00:01 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F1"())
19 rows selected.
SQL> Shows that default selectivity of 5% for an equality predicate against function.
Let's try to adjust the selectivity using associate statistics - the argument for selectivity should be a percentage between 0 and 100:
(turning off cardinality feedback for clarity/simplicity)
SQL> alter session set "_optimizer_use_feedback" = false;
Session altered.
SQL>
SQL> ASSOCIATE STATISTICS WITH FUNCTIONS f1 default selectivity 100;
Statistics associated.
SQL> select count(*) from t1 where col1 >= f1;
COUNT(*)
100000
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID gm7ppkbzut114, child number 1
select count(*) from t1 where col1 >= f1
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 139 (100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 139 (62)| 00:00:01 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F1"())
19 rows selected.
SQL> Didn't make any difference to selectivity.
An excerpt from a 10053 trace file had the following:
** Performing dynamic sampling initial checks. **
** Dynamic sampling initial checks returning FALSE.
No statistics type defined for function F1
No default cost defined for function F1So, crucially what's missing here is a clause saying:
No default selectivity defined for function F1But there's no other information that I could see to indicate why it should be discarded.
Moving on, adjusting the cost does happen:
SQL>exec spflush;
PL/SQL procedure successfully completed.
SQL> disassociate statistics from functions f1;
Statistics disassociated.
SQL>
SQL> ASSOCIATE STATISTICS WITH FUNCTIONS f1 default selectivity 100 default cost (100,5,0);
Statistics associated.
SQL> select count(*) from t1 where col1 >= f1;
COUNT(*)
100000
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID gm7ppkbzut114, child number 0
select count(*) from t1 where col1 >= f1
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 500K(100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 500K (1)| 00:41:41 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F1"())
19 rows selected.
SQL> And we see the following in a 10053:
No statistics type defined for function F1
Default costs for function F1 CPU: 100, I/O: 5So, confirmation that default costs for function were found and applied but nothing else about selectivity again.
I wondered whether the lack of arguments for function F1 made any difference, hence function F2.
Didn't seem to:
Vanilla:
SQL> select count(*) from t1 where col1 >= f2(col1);
COUNT(*)
100000
SQL>
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID 2wxw32wadgc1v, child number 0
select count(*) from t1 where col1 >= f2(col1)
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 139 (100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 139 (62)| 00:00:01 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F2"("COL1"))
19 rows selected.
SQL> Plus association:
SQL>exec spflush;
PL/SQL procedure successfully completed.
SQL>
SQL> associate statistics with functions f2 default selectivity 90 default cost (100,5,0);
Statistics associated.
SQL> select count(*) from t1 where col1 >= f2(col1);
COUNT(*)
100000
SQL>
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID 2wxw32wadgc1v, child number 0
select count(*) from t1 where col1 >= f2(col1)
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 500K(100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 500K (1)| 00:41:41 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F2"("COL1"))
19 rows selected.
SQL> Just to confirm associations:
SQL> select * from user_associations;
OBJECT_OWNER OBJECT_NAME COLUMN_NAME OBJECT_TY
STATSTYPE_SCHEMA STATSTYPE_NAME DEF_SELECTIVITY DEF_CPU_COST DEF_IO_COST DEF_NET_COST
INTERFACE_VERSION MAINTENANCE_TY
RIMS F2 FUNCTION
90 100 5
0 USER_MANAGED
RIMS F1 FUNCTION
100 100 5
0 USER_MANAGED
SQL> So.... started thinking about whether using an interface type would help?
SQL> CREATE OR REPLACE TYPE test_stats_ot AS OBJECT
2 (dummy_attribute NUMBER
3 ,STATIC FUNCTION ODCIGetInterfaces (
4 ifclist OUT SYS.ODCIObjectList
5 ) RETURN NUMBER
6 ,STATIC FUNCTION ODCIStatsSelectivity (
7 pred IN SYS.ODCIPredInfo,
8 sel OUT NUMBER,
9 args IN SYS.ODCIArgDescList,
10 strt IN NUMBER,
11 stop IN NUMBER,
12 --i_col1 in NUMBER,
13 env IN SYS.ODCIEnv
14 ) RETURN NUMBER
15 --,STATIC FUNCTION ODCIStatsFunctionCost (
16 -- func IN SYS.ODCIPredInfo,
17 -- cost OUT SYS.ODCICost,
18 -- args IN SYS.ODCIArgDescList,
19 -- i_col1 in NUMBER,
20 -- env IN SYS.ODCIEnv
21 -- ) RETURN NUMBER
22 );
23 /
Type created.
SQL> CREATE OR REPLACE TYPE BODY test_stats_ot
2 AS
3 STATIC FUNCTION ODCIGetInterfaces (
4 ifclist OUT SYS.ODCIObjectList
5 ) RETURN NUMBER
6 IS
7 BEGIN
8 ifclist := sys.odciobjectlist(sys.odciobject('SYS','ODCISTATS2'));
9 RETURN odciconst.success;
10 END;
11 STATIC FUNCTION ODCIStatsSelectivity
12 (pred IN SYS.ODCIPredInfo,
13 sel OUT NUMBER,
14 args IN SYS.ODCIArgDescList,
15 strt IN NUMBER,
16 stop IN NUMBER,
17 --i_col1 in NUMBER,
18 env IN SYS.ODCIEnv)
19 RETURN NUMBER
20 IS
21 BEGIN
22 sel := 90;
23 RETURN odciconst.success;
24 END;
25 -- STATIC FUNCTION ODCIStatsFunctionCost (
26 -- func IN SYS.ODCIPredInfo,
27 -- cost OUT SYS.ODCICost,
28 -- args IN SYS.ODCIArgDescList,
29 -- i_col1 in NUMBER,
30 -- env IN SYS.ODCIEnv
31 -- ) RETURN NUMBER
32 -- IS
33 -- BEGIN
34 -- cost := sys.ODCICost(10000,5,0,0);
35 -- RETURN odciconst.success;
36 -- END;
37 END;
38 /
Type body created.
SQL> But this approach is not happy - perhaps not liking the function with no arguments?
SQL> disassociate statistics from functions f1;
Statistics disassociated.
SQL> ASSOCIATE STATISTICS WITH FUNCTIONS f1 USING test_stats_ot;
Statistics associated.
SQL> select count(*) from t1 where col1 >= f1;
select count(*) from t1 where col1 >= f1
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-06550: line 12, column 22:
PLS-00103: Encountered the symbol "ÀÄ" when expecting one of the following:
) , * & = - + < / > at in is mod remainder not rem =>
<an exponent (**)> <> or != or ~= >= <= <> and or like like2
like4 likec between || multiset member submultiset
SQL> So, back to F2 again (uncommenting argument i_col1 in ODCIStatsSelectivity):
SQL> disassociate statistics from functions f1;
Statistics disassociated.
SQL> disassociate statistics from functions f2;
Statistics disassociated.
SQL> ASSOCIATE STATISTICS WITH FUNCTIONS f2 USING test_stats_ot;
Statistics associated.
SQL> select count(*) from t1 where col1 >= f2(col1);
COUNT(*)
100000
SQL> select * from table(dbms_xplan.display_cursor);
PLAN_TABLE_OUTPUT
SQL_ID 2wxw32wadgc1v, child number 0
select count(*) from t1 where col1 >= f2(col1)
Plan hash value: 3724264953
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 139 (100)| |
| 1 | SORT AGGREGATE | | 1 | 5 | | |
|* 2 | TABLE ACCESS FULL| T1 | 5000 | 25000 | 139 (62)| 00:00:01 |
Predicate Information (identified by operation id):
2 - filter("COL1">="F2"("COL1"))
19 rows selected.
SQL> Nothing obviously happening.
You'll note also in my interface type implementation that I commented out a declaration of ODCIStatsFunctionCost.
This post is probably already too long already so I've skipped some of the detail.
But when ODCIStatsFunctionCost was used with function F2, I presume I've made a mistake in the implementation because I had an error in the 10053 trace as follows:
Calling user-defined function cost function...
predicate: "RIMS"."F2"("T1"."COL1")
declare
cost sys.ODCICost := sys.ODCICost(NULL, NULL, NULL, NULL);
arg0 NUMBER := null;
begin
:1 := "RIMS"."TEST_STATS_OT".ODCIStatsFunctionCost(
sys.ODCIFuncInfo('RIMS',
'F2',
NULL,
1),
cost,
sys.ODCIARGDESCLIST(sys.ODCIARGDESC(2, 'T1', 'RIMS', '"COL1"', NULL, NULL, NULL))
, arg0,
sys.ODCIENV(:5,:6,:7,:8));
if cost.CPUCost IS NULL then
:2 := -1.0;
else
:2 := cost.CPUCost;
end if;
if cost.IOCost IS NULL then
:3 := -1.0;
else
:3 := cost.IOCost;
end if;
if cost.NetworkCost IS NULL then
:4 := -1.0;
else
:4 := cost.NetworkCost;
end if;
exception
when others then
raise;
end;
ODCIEnv Bind :5 Value 0
ODCIEnv Bind :6 Value 0
ODCIEnv Bind :7 Value 0
ODCIEnv Bind :8 Value 4
ORA-6550 received when calling RIMS.TEST_STATS_OT.ODCIStatsFunctionCost -- method ignoredThere was never any such feedback about ODCIStatsSelectivity.
So, in summary, more questions than answers.
I'll try to have another look later. -
Replace function not working for XML CLOB data
Hi all,
I am generating XML using DBMS_XMLGEN in oracle 10g. After generating the XML, I am replacing the ROW tags with appropriate tag name using REPLACE function. Sometimes the tag name is not replaced correctly.
Eg.I am replacing </Cargo_ROW> with </CargoDetail>. But sometimes in one xml, this tag is coming as </CargoDetROW> or </CargoDetaiW>. The XML size is always huge and the same tag is repeated so many time in the loop and in the same XML, only one tag will be replaced incorrectly. This also not happening for all XMLs.
If any one knows the cause about this problem or solution, please share the same.
thanks,Yes Anton, you are right..
It was typecasting problem
replace supports clob
Check this out
SQL> declare
2 xmldata clob;
3 Begin
4 xmldata:='<Message transaction_log_id="" extraction_date="25/11/09 09:52:03 AM" versio
5 <Transaction>
6 <TransactionType>ORIGINAL</TransactionType>
7 <ControlNumber>60022449779</ControlNumber>
8 <BookingHeader>
9 <PortCodeOriginal>GBSOU</PortCodeOriginal>
10 <Contact>.</Contact>
11 <PhoneContact>.</PhoneContact>
12 </BookingHeader>
13 <PartyInformation>
14 <PartyDetails>
15 <PartyId>10002866</PartyId>
16 <Type>SHIP</Type>
17 <Name1>L LTD.</Name1>
18 </PartyDetails>
19 </PartyInformation>
20 <Cargo>
21 <CargoDetROW>
22 <CargoHeader>
23 <CargoReceivedSeqNo>600015391790</CargoReceivedSeqNo>
24 <CargoId>RW9330P013948</CargoId>
25 </CargoHeader>
26 <CargoDimensions>
27 <Length>1</Length>
28 <Width>2</Width>
29 </CargoDimensions>
30 </CargoDetail>
31 <CargoDetROW>
32 <CargoHeader>
33 <CargoReceivedSeqNo>600015391791</CargoReceivedSeqNo>
34 <CargoId>RW9330P01394AA</CargoId>
35 </CargoHeader>
36 <CargoDimensions>
37 <Length>2</Length>
38 <Width>2</Width>
39 </CargoDimensions>
40 </CargoDetail>
41 <Cargo_ROW>
42 <CargoHeader>
43 <CargoReceivedSeqNo>600015391792</CargoReceivedSeqNo>
44 <CargoId>RW9330P01322</CargoId>
45 </CargoDetaiW>
46 <CargoDimensions>
47 <Length>1</Length>
48 <Width>2</Width>
49 </CargoDimensions>
50 </Cargo_ROW>
51 </Cargo>
52 </Transaction>
53 </Message>';
54 xmldata:=to_clob(regexp_replac(xmldata,'</Cargo_ROW>|</CargoDetaiW>|</CargoDetROW>','</CargoDetail'));
55 xmldata:=to_clob(regexp_replace(xmldata,'<Cargo_ROW>|<CargoDetaiW>|<CargoDetROW>','<CargoDetail>'));
56 dbms_output.put_line(xmldata);
57 end;
58 /
<Message transaction_log_id="" extraction_date="25/11/09 09:52:03 AM"
version="1.0">
<Transaction>
<TransactionType>ORIGINAL</TransactionType>
<Contro
lNumber>60022449779</ControlNumber>
<BookingHeader>
<PortCodeOriginal>GBSOU</Por
tCodeOriginal>
<Contact>.</Contact>
<PhoneContact>.</PhoneContact>
</BookingHead
er>
<PartyInformation>
<PartyDetails>
<PartyId>10002866</PartyId>
<Type>SHIP</Ty
pe>
<Name1>L
LTD.</Name1>
</PartyDetails>
</PartyInformation>
<Cargo>
<CargoDetail>
<CargoHea
der>
<CargoReceivedSeqNo>600015391790</CargoReceivedSeqNo>
<CargoId>RW9330P01394
8</CargoId>
</CargoHeader>
<CargoDimensions>
<Length>1</Length>
<Width>2</Width>
</CargoDimensions>
</CargoDetail>
<CargoDetail>
<CargoHeader>
<CargoReceivedSeq
No>600015391791</CargoReceivedSeqNo>
<CargoId>RW9330P01394AA</CargoId>
</CargoHe
ader>
<CargoDimensions>
<Length>2</Length>
<Width>2</Width>
</CargoDimensions>
<
/CargoDetail>
<CargoDetail>
<CargoHeader>
<CargoReceivedSeqNo>600015391792</Carg
oReceivedSeqNo>
<CargoId>RW9330P01322</CargoId>
</CargoDetail>
<CargoDimensions>
<Length>1</Length>
<Width>2</Width>
</CargoDimensions>
</CargoDetail>
</Cargo>
</Transaction>
</Message>
PL/SQL procedure successfully completed.
SQL> Twinkle
Edited by: Twinkle on Nov 26, 2009 6:05 PM
Maybe you are looking for
-
My iphone 5 is getting stuck in sync mode
Please help me to fix this problem.
-
Requests in phase completed with status warning and there is no output
Hi guys, While running some requests, they complete with a warning and there is no output to view. The request log doesn't show any significant errors. What could be the reason for this and how can I troubleshoot this problem? This is the content of
-
Embed html code with Oracle Apex report
hello Everybody, Iam wondering if you guys have any idea about embeding my own html code that has a javascript and html stuff in Oracle Apex page. Thanks, Abdul ALkhateeb
-
J2SE Daylight Time Update -mIssing patch/packages
I have been testing the patch install for J2SE on Solaris 9 and it isn't working. Before installing, I checked the version: forest:hughesm> java -version java version "1.4.0_00" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0_00-b05) Ja
-
Sat Pro M10 P-M 1.3 Modem Problems
I suffered an online freeze when on a dial up connection with the internal modem. Cursor froze, programs froze and task manager would not start modem icons were both glowing as if sending data. I eventually pulled the modem cable out (icond still ind