Using function in where clause
I have created a function as follows
create or replace FUNCTION get_codes RETURN varchar2 IS
scodes varchar2(50) := 'A1,A2';
BEGIN
scodes := '('''||REPLACE(scodes,',',''',''')||''')';
return scodes;
END;
this function returns ('A1','A2')
now i want to use this in where clause, both below statements fetches no rows
select * from tablea where code in (select get_codes from dual);
select * from tablea where code in get_codes;
but the following will fetch rows
select * from tablea where code in ('A1','A2')
how to use function in where clause
Thanks
Hi,
The code that works:
where code in ('A1','A2')is testing whther code is either of two 2-character strings, A1 or A2.
The ones that don't work, such as:
where code in get_codes;are comparing code to one 9-character string: 'A1','A2', where characters 1, 4, 6 and 9 are single-quotes. (The function can only return one value.)
You can use dynamic SQL to embed that 9-character string in part of your query, where it will be interpreted as two 2-character strrings.
[Oracle Base|http://www.oracle-base.com/articles/misc/DynamicInLists.php] and AskTom have good pages on the subject of dynamic IN-lists.
Of you can use INSTR or LIKE:
where INSTR ( get_codes
, '''' || code || ''''
) > 0
Similar Messages
-
Clarification on using function in where clause of oracle sql query
I have an issue in regarding function using where clause of sql query..
We are facing performance issue while executing query, so in what ways to improve the performance of the query which i have posted below.
select col ,case when my_function(parameter)
from tab1 a ,tab2 b,tabl3 c
where a.column1=b.column2
and b.column3 =c.column6
and my_function(parameter)>0
Regards
Dinesh
Edited by: wild fire on May 18, 2012 4:15 PMDinesh,
remind that when you use a function in the where clause it normally will get started for each record in the table.
So your answer is two-fold:
1. make the function only start when needed by adding a function based index on the table (this will make inserts and updates slower)
2. make the function faster by adding the DETERMINISTIC clause if possible. this will make Oracle "cache" the result of the function.
Regards,
Richard
blog: http://blog.warp11.nl
twitter: @rhjmartens
If this question is answered, please mark the thread as closed and assign points where earned.. -
Regd. using functions in where clause
Hi All,
I need to apply a set of functions in sysdate and use that in a where clause to compare. My question is, will these functions on sysdate be executed for every record in the tables that I use? Will this have performance impact when i have millions of records returned by the select?
Below is the scenario:
Select * from table A inner join table B on A.c1 = B.c1 where
TO_NUMBER(TO_CHAR(TRUNC(LAST_DAY(ADD_MONTHS(SYSDATE, -1))),'YYYYMMDD')) BETWEEN Date1 and Date2
Regards,
Raj.D1005330 wrote:
I need to apply a set of functions in sysdate and use that in a where clause to compare. My question is, will these functions on sysdate be executed for every record in the tables that I use? Will this have performance impact when i have millions of records returned by the select?
Below is the scenario:
Select * from table A inner join table B on A.c1 = B.c1 where
TO_NUMBER(TO_CHAR(TRUNC(LAST_DAY(ADD_MONTHS(SYSDATE, -1))),'YYYYMMDD')) BETWEEN Date1 and Date2
Test it on a small data set - run a query and check the execution plan to see what the predicate section tells you.
Oracle OUGHT to be smart enough to recognise that you've got a constant that it need only calculate once. If not, then change the usage to read:
(select TO_NUMBER(TO_CHAR(TRUNC(LAST_DAY(ADD_MONTHS(SYSDATE, -1))),'YYYYMMDD')) from dual) BETWEEN Date1 and Date2Note, by the way, that 'constant between col1 and col2' is generally a tough one as far as efficiency is concerned; it translates to:
col1 <= constant
and col2 >= constantIn many cases this means oracle has to access a large volume of data (for one of the predicates) and then filter that data (with the other predicate). A typical damage limitation strategy is to create an index on the two columns, arrangin the column order to minimise the range scan on the first column.
Depending on your data patterns and the nature of the predicate there are alternative optimiisation strategies.
Regards
Jonathan Lewis -
!! Getting error while using function in where clause
Hi,
I have created a function as below
create function find_cnt(n varchar2)
return number is
cnt number;
begin
execute immediate 'select count(1) from '||n into cnt;
return nvl(cnt,0);
end;
and when running the below select
select find_cnt(object_name),object_name from user_objects where object_type='TABLE' and find_cnt(object_name)=0
I getting
ERROR:
ORA-04044: procedure, function, package, or type is not allowed here
ORA-06512: at "SCOTT.FIND_CNT", line 5
can anyone help????????
thanks
HarishIn 11g you could simply do
SQL> select table_name, trim(column_value) cnt
from user_tables, xmltable(('count(ora:view("'||table_name||'"))'))
TABLE_NAME CNT
DEPT 4
BONUS 0
SALGRADE 5
DEMO_USERS 2
DEMO_CUSTOMERS 7
DEMO_ORDERS 10
DEMO_PRODUCT_INFO 10
DEMO_ORDER_ITEMS 16
DEMO_STATES 51
DEMO_PAGE_HIERARCHY 18
TABLE1 6
TABLE2 6
CREATE$JAVA$LOB$TABLE 0
CLICKS 1
T 0
EMP 14
PLAN_TABLE 2
17 rows selected. -
Strange errors when using user defined function in where clause
Hello,
I am having trouble with a function that, when used in the where clause of a select will cause an error if the first column selected is of type INTEGER. Not sure whether I am doing something wrong or whether this is a bug.
Here is a very simple test case:
create table test(
col1 integer not null,
col2 varchar(20) ascii default ''
insert into test values(1,'2011-03-15 05:00:00')
insert into test values(2,'2011-03-15 07:00:00')
CREATE FUNCTION BTR_TAG RETURNS VARCHAR AS
VAR ret VARCHAR(20);
SET ret='2011-03-15 06:00:00';
RETURN ret;
Select * from test where col2 >= BTR_TAG()
Select col1,col2 from test where col2 >= BTR_TAG()
=> Error in assignment;-3016 POS(1) Invalid numeric constant
Select '',* from test where col2 >= BTR_TAG()
Select col2,col1 from test where col2 >= BTR_TAG()
=> works as it should
MaxDB V 7.7.07.16 running on Windows Server 2003
I can replicated the test case above with Sql Studio and other ODBC based tools.
Thanks in advance,
Silke ArnswaldHello Siva,
sorry, but I don't understand your reply:
This is not right forum to posting this question.
You are from which module or working any 3rd party application.
MaxDB 7.7.07.16 is the community version of MaxDb,
we are not using it for SAP
and no 3rd party software is required to reproduce my problem,
Sql Studio or Database Studio will do.
Regards,
Silke Arnswald -
Can you use boolean function in where clause
Hi,
I have a boolean function. Is it possible to use it in where clause of query.
Eg;
is_prime(13) returns boolean
select 1 from dual where is_prime(13)What about something like this
Create or replace function boolret(id number) return boolean as
begin
If id <10 then
return true;
elsif id>10 and id<100 then
return false;
else
return null;
end if;
end;
1 declare
2 id_cat boolean;
3 begin
4 id_cat:= boolret(8);
5 dbms_output.put_line(id_cat);
6* end;
SQL> /
dbms_output.put_line(id_cat);
ERROR at line 5:
ORA-06550: line 5, column 2:
PLS-00306: wrong number or types of arguments in call to 'PUT_LINE'
ORA-06550: line 5, column 2:
PL/SQL: Statement ignored
It seems PL/Sql doesn't have any datatype like Boolean,But it handles Boolean like datatype.
Regards
Raj deep.A -
Using round off function in where clause
Hi All,
I'm trying to use round off function in where clause, I seek help in completing this script.
WITH CR_Details AS
(Select
request_id,
parent_request_id,
fcpt.user_concurrent_program_name Request_Name, phase_code, status_code,
round((fcr.actual_completion_date - fcr.actual_start_date),3) * 24 * 60 as Run_Time,
round(avg(round(to_number(actual_start_date - fcr.requested_start_date),3) * 1440),2) wait_time,
fu.User_Name Requestor,
fcr.argument_text parameters,
to_char (fcr.requested_start_date, 'MM/DD HH24:mi:SS') requested_start,
to_char(actual_start_date, 'MM/DD/YY HH24:mi:SS') ACT_START,
to_char(actual_completion_date, 'MM/DD/YY HH24:mi:SS') ACT_COMP,
fcr.completion_text
From
apps.fnd_concurrent_requests fcr,
apps.fnd_concurrent_programs fcp,
apps.fnd_concurrent_programs_tl fcpt,
apps.fnd_user fu
Where 1=1
and fcr.concurrent_program_id = fcp.concurrent_program_id
and fcp.concurrent_program_id = fcpt.concurrent_program_id
and fcr.program_application_id = fcp.application_id
and fcp.application_id = fcpt.application_id
and fcr.requested_by = fu.user_id
and fcpt.language = 'US'
and fcr.actual_start_date like sysdate )
select crd.*
from CR_Details crd
where Run_time <> '0'
AND wait_time <> '0'
GROUP BY
crd.request_id,
crd.parent_request_id,
crd.fcpt.user_concurrent_program_name,
crd.requested_start_date,
crd.User_Name,
crd.argument_text,
crd.actual_completion_date,
crd.actual_start_date,
crd.phase_code,
crd.status_code,
crd.resubmit_interval,
crd.completion_text,
crd.resubmit_interval,
crd.resubmit_interval_unit_code,
crd.description
Not sure about the GROUPBY function referencing the "crd." .Hi,
The best thing for you to do is start over. Start as small as possible, then take baby steps.
Pick one of the tables; fcr perhaps, and write a query that just uses that table, like this:
SELECT *
FROM apps.fnd_concurrent_requests fcr
WHERE fcr.actual_start_date >= TRUNC (SYSDATE)
AND fcr.actual_start_dt < TRUNC (SYSDATE) + 1
;(I think this is what you meant to do when you said "... LIKE SYSDATE".)
Make sure this little query gets credible results. When that tiny query is working perfectly, add another line or two. You can cut and paste code from what you posted, if that helps you.
If you get stuck, post the last version of your code that worked perfectly, and the latest version (only a line or two bigger) that has the problem. Describe what the problem is. If you get an error, post the complete error message. In any event, post CREATE TABLE and INSERT statements for all the tables and columns needed to run the query, and the results you want to get from that query.
When you post any code, format it, so that how the code looks on the screen gives some clues about how it is working.
When you post any formatted text on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
If you going to use the AVG function in the sub-query, then you probably need to do a GROUP BY in the sub-query.
If you're not using any aggregate functions (like AVG) in the main query, then you probably don't want to do a GROUP BY in the main query.
I know this is a lot of work. I'm sorry. If there was an easier way, I wouldn't ask you to do all this. -
How can we use DECODE function in where clause.
Hi Guys,
I have to use DECODE function in where clause.
like below
select * from tab1,tab2
where a.tab1 = b.tab2
and decode(code, 'a','approved')
in this manner its not accepting?
Can any one help me on this or any other aproach?
Thanks
-LKR>
I am looking for to decode the actual db value something in different for my report.
like if A then Accepted
elseif R then Rejected
elseif D then Denied
these conditions I have to check in where clause.
>
what are you trying to do?
may be you are looking for
select * from tab1,tab2
where a.tab1 = b.tab2
and
(decode(:code, 'A','Accepted') = <table_column>
or
decode(:code, 'R','Rejected') = <table_column>
or
decode(:code, 'D','Denied') = <table_column>
) -
Can't have aggregate function in WHERE clause clause
Dear all,
I've created object in BO XI 3.1 Designer with following criterias:
http://img4.imageshack.us/img4/833/20111201124314.th.jpg
It is a simple number - 1,2,3,4,5.
Now I need to use this object as a criteria for WHERE function in another object.
http://img607.imageshack.us/img607/1543/20111201124717.th.jpg
I receive an error "Can't have aggregate function in WHERE clause <clause>"
How can I overcome this?
P.S. I'm sorry in advance if such topic already exist - I didn't found one.
Edited by: Ashot Antonyan on Dec 1, 2011 9:50 AM
Edited by: Ashot Antonyan on Dec 1, 2011 9:51 AMHi,
You will have to use Sub query to achieve this. Give more details on what is available and what you need then i could help you out with the complete solution.
Thanks,
Ravichandra K -
Help:alternate for calling function in where clause
Hi ,
In below query i'm calling function in where clause to avoid COMPLETE status records,due to this query taking 700 secs to return result.If i'm remove below function condition it's returning results with in 5 secs.Can you some one advice to any alternate idea for this?
WHERE mark_status != 'COMPLETE'
SELECT assessment_school,
subject,
subject_option,
lvl,
component,mark_status,
mark_status
NULL AS grade_status,
NULL AS sample_status,
:v_year,
:v_month,
:v_formated_date,
:v_type,
cand_lang
FROM
(SELECT assessment_school,
subject,
subject_option,
lvl,
programme,
component,
paper_code,
cand_lang,
mark_entry.get_ia_entry_status(:v_year, :v_month, assessment_school, subject_option, lvl, cand_lang, component, paper_code) AS mark_status
FROM
(SELECT DISTINCT ccr.assessment_school,
ccr.subject,
ccr.subject_option,
ccr.lvl,
ccr.programme,
ccr.language AS cand_lang,
ccr.paper_code,
ccr.component
FROM candidate_component_reg ccr
WHERE ccr.split_session_year = :v_year
AND ccr.split_session_month = :v_month
AND EXISTS
(SELECT 1
FROM IBIS.subject_component sc
WHERE sc.year = ccr.split_session_year
AND sc.month = ccr.split_session_month
AND sc.paper_code = ccr.paper_code
AND sc.assessment_type = 'INTERNAL'
AND sc.subject_option NOT LIKE '%self taught%'
AND sc.component NOT IN ('PERFORMANCE PRODUCTION','PRESENTATION WORK','REFLECTIVE PROJECT','SPECIAL SYLLABUS INT. ASSESSMENT')
AND NVL(ccr.withdrawn,'N') = 'N'
AND ccr.mark_status != 'COMPLETE'
AND EXISTS
(SELECT 1
FROM school s
WHERE s.school_code = ccr.assessment_school
AND s.training_school = 'N'
WHERE mark_status != 'COMPLETE';One thing you can test quickly is to put the function call in it's own select ...from dual.
This might make a difference.
However, only you can check this, I don't have your tables or data.
So, what happens if you use:
paper_code,
cand_lang,
(select mark_entry.get_ia_entry_status(:v_year, :v_month, assessment_school, subject_option, lvl, cand_lang, component, paper_code) from dual ) AS mark_status
FROM
(SELECT DISTINCT ccr.assessment_school, --<< is the DISTINCT really needed?
ccr.subject,
ccr.subject_option,
...Also, try to find out the purpose of that above DISTINCT, is it really needed or is there some join missing? -
My function in where clause? help me please.
hello friends, I need to call my function in where clause as dummy example below:
declare
name_ table1.name%type;
function return_id(id number) return number is
begin
return 1;
end return_id;
begin
select name into name_
from table1
where id = return_id(table1.id);
end;
raise exception: 'the function doesn't used in where clause'. why????-- CREATING A FUNCTION AVAILABLE THROUGH A PACKAGE SPEC.
SQL> ed
Wrote file afiedt.buf
1 create package mypackage is
2 function myfunc(p_val NUMBER) RETURN NUMBER;
3* end;
SQL> /
Package created.
SQL> ed
Wrote file afiedt.buf
1 create or replace package body mypackage is
2 function myfunc(p_val NUMBER) RETURN NUMBER IS
3 begin
4 RETURN (p_val*p_val)-1;
5 end;
6* end;
SQL> /
Package body created.
SQL> declare
2 v_myval NUMBER := 2;
3 begin
4 select mypackage.myfunc(v_myval)
5 into v_myval
6 from dual;
7 dbms_output.put_line(v_myval);
8 select mypackage.myfunc(v_myval)
9 into v_myval
10 from dual;
11 dbms_output.put_line(v_myval);
12 end;
13 /
3
8
PL/SQL procedure successfully completed.
-- CREATING A STANDALONE DATABASE FUNCTION.
SQL> create or replace function myfunc2(p_val number) return number is
2 begin
3 return (p_val*2)+1;
4 end;
5 /
Function created.
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_myval NUMBER := 2;
3 begin
4 select myfunc2(v_myval)
5 into v_myval
6 from dual;
7 dbms_output.put_line(v_myval);
8 select myfunc2(v_myval)
9 into v_myval
10 from dual;
11 dbms_output.put_line(v_myval);
12* end;
SQL> /
5
11
PL/SQL procedure successfully completed.
-- CREATING A LOCAL FUNCTION IN THE ANONYMOUS PL/SQL BLOCK
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_myval NUMBER := 2;
3 function myfunc3(p_val number) return number is
4 begin
5 return (p_val*p_val*p_val);
6 end;
7 begin
8 select myfunc3(v_myval)
9 into v_myval
10 from dual;
11 dbms_output.put_line(v_myval);
12 select myfunc3(v_myval)
13 into v_myval
14 from dual;
15 dbms_output.put_line(v_myval);
16* end;
SQL> /
select myfunc3(v_myval)
ERROR at line 8:
ORA-06550: line 8, column 10:
PLS-00231: function 'MYFUNC3' may not be used in SQL
ORA-06550: line 8, column 10:
PL/SQL: ORA-00904: : invalid identifier
ORA-06550: line 8, column 3:
PL/SQL: SQL Statement ignored
ORA-06550: line 12, column 10:
PLS-00231: function 'MYFUNC3' may not be used in SQL
ORA-06550: line 12, column 10:
PL/SQL: ORA-00904: : invalid identifier
ORA-06550: line 12, column 3:
PL/SQL: SQL Statement ignored
SQL>As you can see (and as previously mentioned by someone else) the function has to be available to the SQL engine either via a datavbase package or as a database function. If you declare the function locally within the anonymous PL/SQL block then the function only exists in the scope of that PL/SQL block and thus when your SQL statement is sent to the SQL engine for execution, the SQL engine can't see it.
;) -
Hi All,
Can anyone know how to use the user defined function in the where clause of the SQL statement.
Thanks in Advance,
Madhu N.Hi,
Boolean is a pls variable.. and cannot be used in a where clause returned from a function.
Simple can we define a variable of type boolean in sql*plus?
Rgds
Srinivas.. -
i insert the below rows in a table cash_book.
PRJ_CODE PRJ_NAME
1203 SHIFA
1203 SHIFA
1203 SHIFA
1202 FATIMA
1202 FATIMA
1203 SHIFA
if i select 1202 code then return 1202 code rows, if i select 1203 then returns 1203 code rows, if i select other than both values then returns all rows. how can i define in one query with use (case or decode function) in where clause ??perhaps something like this:
create table test
as
select 1200 + rownum prj_code
from dual
connect by level <= 10;
select * from test;
PRJ_CODE
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
var v_PRJ_CODE number
exec :v_PRJ_CODE := 1200;
select *
from test
where PRJ_CODE = :v_PRJ_CODE
or 1 = case when :v_PRJ_CODE in (1202, 1203) then 0 else 1 end;
PRJ_CODE
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
exec :v_PRJ_CODE := 1203;
select *
from test
where PRJ_CODE = :v_PRJ_CODE
or 1 = case when :v_PRJ_CODE in (1202, 1203) then 0 else 1 end;
PRJ_CODE
1203Regards
Martin -
Hello all,
I am new to Oracle, currently using 10G + aspvbscript.
I've been trying to query data using date in where clause but nothing seems to work.
The column is in date format.
It gets printed out like this: 5/1/2010 11:21:19 AM
I tried using this query:
SELECT * from table where TRUNC(user_date) > to_date('FEB-01-2010:00:00:00','mm-dd-yyyy:HH24:MI:SS') order by user_date asc.
It does return an output but it returns everything in table and does not take WHERE clause into consideration however, it does sort the date in ascending order.
I've tried getting rid of TRUNC tried to format date in a different way but no such luck.
Please point me to the right direction.
Thanks.Welcome to the forums!
In cases like this it is helpful if you can provide the following information:
1. Oracle version (SELECT * FROM V$VERSION)
2. Sample data in the form of CREATE / INSERT statements.
3. Expected output
4. Explanation of expected output (A.K.A. "business logic")
5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
I'll try and take a stab at your request based on the data given. What your query says is that it will return all rows that have a date greater then 2/1/2010 (MM/DD/YYYY). If your query is returning all rows then maybe the possibility exists that all the dates in the table are greater then 2/1/2010. Have you checked all dates to see if this is the case?
Also, one note about your TO_DATE() function.to_date('FEB-01-2010:00:00:00','mm-dd-yyyy:HH24:MI:SS')The date format does not match the string you are using with respect to month. Your string has 'FEB' but the format is 'MM' which is the numeric representation of the month. Although Oracle was able to convert it to the proper date on my system you should try and maintain consistency between the string and the date format used. -
Can both in-row and off-row LOBs be used in a where clause?
We are preparing to upgrade ASE from version 15.5 to 16.0. One of the features that is very appealing has to do with the changes made concerning the handling of LOBs. In particular, the ability to use a LOB column in search arguments (where clause) is something our developers have longed for since the retirement of the full-text search option. So, in version 16.0, can any column with a datatype of text be used as a search argument? Are there any restrictions.
Thanks in advance.Hi Kevin,
The in-row LOB feature is mainly designed to save space when a text column has many short values, which is a particularly bad problem when the server uses a large page size (like 16K) as ASE would use a full 16K to store even a single bye "Y". I don't think the feature made any change in how text can be used in search arguments. i.e. you can still use LIKE and IS [NOT] NULL, but not others.
Example:
1> create table t (x text in row (8))
2> go
1> insert t values ("abc")
2> insert t values ("abcdefghijkl")
3> go
(2 rows affected)
1> select * from t where x like "%c%"
2> go
x
abc
abcdefghijkl
(2 rows affected)
1> select * from t where x !> "c"
2> go
Msg 257, Level 16, State 1:
Server 'redhead', Line 1:
Implicit conversion from datatype 'TEXT' to 'VARCHAR' is not allowed. Use the
CONVERT function to run this query.
Msg 306, Level 16, State 5:
Server 'redhead', Line 1:
TEXT, IMAGE and UNITEXT datatypes may not be used in a WHERE clause, except with
the LIKE expression and IS [NOT] NULL predicate on columns.
Maybe you are looking for
-
Hi, I have just bought an ATI X800 Pro. Using the newest Catalyst drivers (5.7 , tried older too but same problem) and the latest JRE as of today. But: every website or application on my PC that uses Java causes a direct BSOD with failing dll 'ati3du
-
Table background colors and images
This should be easy, but I am not seeing it. I have a few pages with existing tables, probably created in DW CS3. In DW CS4, I need to select a table inside a cell of another table and assign a solid color for the background. Currently, the larger ta
-
Set deadline according to factory calendar
Hi workflow experts, I have 3 questions regarding deadline monitoring. 1. Is it possible to use bussiness days from factory calendar instead of calendar days for workitem deadline ? 2. Is there a FB for changing the deadline of a workitem ? I found o
-
Aperture 3 - stuck "Updating Library" Processing images
My Aperture 3 Library says it is Updating Library Processing 93,182 items. It gets stuck at 268 of 93,182 and stops. If I try to Export anything the Activity Monitor shows it is processing the Export, however nothing happens. I have to Force Quit at
-
Canvio 500GB NTI Backup Now EZ
I want to uninstall NTI Backup Now. When I try to uninstall, I get an error message: "Error reading setup initialization file". I have re-installed the program and still get this message. I really don't care for this program, it causes my laptop t