Use realational operators in an SQL query??????
does any one knows how to use realational operators in an SQL query??????
i wud like to do something like
select decode(2<3,sysdate,sydate +1) from dual
but i know decode does not supports relational operators......
thanx and Regards
amyt
You can use a CASE statement which does support relational operators, or if you must use DECODE, then you can use something like:
SELECT DECODE(SIGN(2 - 3),-1,sysdate,sysdate - 1)
FROM dual;The SIGN function returns -1 if the expression is < 0, 1 if the expression is > 0 and 0 if the expression is 0. This works for numeric comparisions. You can use the GREATEST or LEAST functions in a similar fashion for character comparisions.
TTFN
John
Similar Messages
-
How to Use the Procedures in a Sql Query
Hi Friends,
Can anyone help me out whether can we use the procedure in the sql query..
if yes help me out with an example
my requirement is
i have one sql query .. in which i need to use the procedure which returns multiple values... how can i overcome it,can anyone help me out for this..
for your reference i am pasting the sql query
SELECT paf.person_id
FROM per_all_assignments_f paf START WITH paf.person_id = p_person_id
AND paf.primary_flag = 'Y'
AND paf.assignment_type IN('E', 'C')
AND l_effective_date BETWEEN paf.effective_start_date
AND paf.effective_end_date
CONNECT BY PRIOR paf.supervisor_id = paf.person_id
AND paf.primary_flag = 'Y'
AND paf.assignment_type IN('E', 'C')
AND l_effective_date BETWEEN paf.effective_start_date
AND paf.effective_end_date
and paf.person_id not in (>>>I HAVE TO USE THE PROCEDURE HERE<<<<);
Thanks in advanceWe never saw your procedure, but maybe you could wrap it in a function
SQL> create or replace procedure get_members(in_something IN number, out_members OUT sys_refcursor)
is
begin
open out_members for
'select level member_id from dual connect by level <= :num' using in_something;
end get_members;
Procedure created.
SQL> create or replace type numbers as table of number;
Type created.
SQL> create or replace function members(in_something IN number)
return numbers
as
member_cur sys_refcursor;
members numbers;
begin
get_members(in_something, member_cur);
fetch member_cur bulk collect into members;
close member_cur;
return members;
end;
Function created.
SQL> select * from table(members(4));
COLUMN_VALUE
1
2
3
4
4 rows selected.Variant on same using piplined function
SQL> create or replace function members_piped(in_something IN number)
return numbers pipelined
as
member_cur sys_refcursor;
rec number;
begin
get_members(in_something, member_cur);
loop
fetch member_cur into rec;
exit when member_cur%notfound;
pipe row(rec);
end loop;
close member_cur;
return;
end;
Function created.
SQL> select * from table(members_piped(4));
COLUMN_VALUE
1
2
3
4
4 rows selected.
SQL> drop function members_piped;
Function dropped.
SQL> drop function members;
Function dropped.
SQL> drop type numbers;
Type dropped.
SQL> drop procedure get_members;
Procedure droppedEdit:
Sorry Blu, had not seen you already posted similar thing
Edited by: Peter on Jan 27, 2011 5:38 AM -
Using System Variables in a SQL Query
Hi!
I´m new to Oracle and SQL so i don´t know very much about it.
There is miy Problem:
Is there a way to Use the System Variable %USERNAME% in an SQL Query?
I tried .... where table.shorttag = '%USERNAME%' ;
but this doesnt work.
Is Oracle able to handle Systemvariables? Or is there another way to use the current Windows User in an SQL Query.
It is very Important to use the current Windows user and not the Oracle user.
Thank you,
MfgAre you looking for something like this ?
SQL> SELECT sys_context('USERENV', 'OS_USER') FROM dual;
SYS_CONTEXT('USERENV','OS_USER
SAUBBANE\IBM
SQL> SELECT sys_context('USERENV', 'TERMINAL') FROM dual;
SYS_CONTEXT('USERENV','TERMINA
SAUBBANEAlso you can look at the dbms_application_info package. -
Using IN keyword in an sql query in a view criteria
Hi,
I am using jdev 11.1.1.1.0 and defined an lov query/viewobject as
select a, b, c from myTable
I now need to predefine filtering for lov search functionality and need something like the following
select a, B, c from myTable where B in ('X','Y')
I could not find a way to do it (i.e. specify the use of IN Keyword) in the Create View Criteria dialog box. I tried to define OR, but is that the best way to redefine IN as i have a long list (the above is just an example)
(( ( (UPPER(B_FLAG) = UPPER('X') ) ) OR ( (UPPER(DISPLAY_FLAG) = UPPER('Y') ) ) ))If you know how many variables are in your "in" You can just write this in the sql query of your VO:
http://www.oracle.com/technology/obe/obe11jdev/ps1/ria_application/images/t136.gif
From this tutorial:
http://www.oracle.com/technology/obe/obe11jdev/ps1/ria_application/developriaapplication_long.htm#ah1 -
Is there any way to use Control Break in a SQL Query
Hi,
Is there any way to use a control break on Dept column in a SQL query to have a Output-2 instead of Output-1.
Is there any way to modify the SQL query.
SQL
select dept, loc, count(*)
from dept
group by dept, locOutput-1
Dept Loc Count(*)
10 AA 1
10 BB 2
10 CC 2
20 AA 2
20 BB 2Output-2
Dept Loc Count(*)
10 AA 1
BB 2
CC 2
20 AA 2
BB 2Thanks,
DeepakDeepakJ wrote:
Hi,
Is there any way to use a control break on Dept column in a SQL query to have a Output-2 instead of Output-1.
Is there any way to modify the SQL query.
SQL
select dept, loc, count(*)
from dept
group by dept, locOutput-1
Dept Loc Count(*)
10 AA 1
10 BB 2
10 CC 2
20 AA 2
20 BB 2Output-2
Dept Loc Count(*)
10 AA 1
BB 2
CC 2
20 AA 2
BB 2
Yes, using the <tt>lag</tt> analytic function and specified ordering of the data:
select
nullif(d.deptno, lag(d.deptno) over (order by d.deptno, d.loc, e.mgr nulls first)) deptno
, nullif(d.loc, lag(d.loc) over (order by d.deptno, d.loc, e.mgr nulls first)) loc
, e.mgr
, count(*) n
from
dept d
join emp e
on d.deptno = e.deptno
group by
d.deptno
, d.loc
, e.mgr
order by
d.deptno
, d.loc
, e.mgr nulls first;
DEPTNO LOC MGR N
10 NEW YORK 1
7782 1
7839 1
20 DALLAS 7566 2
7788 1
7839 1
30 CHICAGO 7698 4
7839 1
40 BOSTON 7698 2
7902 1 -
Use of FIELD in Attribute SQL Query
Hi folks,
Back in 7.1 you could use %FIELD.[attributename]% in a sql query defining an identity store attribute's values.
Does anyone know if this functionality was lost in 7.2? Can't seem to get it to work.
Thanks,
MattHi Moritz,
did you consider that note:
Note: Both
fields must be
defined as "Single value" with presentation type "Single select"?
It does not work as soon as you use other storage or presentation types.
Regards
Norman -
Using Multi Select List in SQL Query
Hi all,
I am trying to using a Multi Select list for filtering of a report. I have :P2_RISK_SEVERITY which has has the possibility of values Very Low:Low:Medium:High:Very High. How do I use this Multi Select in the where section of a SQL query?
I need to say something along the lines of:
Select RISK_SEVERITY from TBL_RMD_RISKS where RISK_SEVERITY = (one of the options selected in the multi select)
Thanks for the help.Hi there,
The above suggestion will work perfectly as long as the table you're querying is relatively small, but keep in mind that applying the INSTR to the left side of the WHERE clause will always result in a full table scan. This means that if your table is large and RISK_SEVERITY is indexed, the index will never be used. Here is another approach (credit to AskTom) that converts your colon-delimited string of selected values to a list that can be used in an "IN(...)" clause, which will use an index on RISK_SEVERITY as long as the optimizer otherwise deems it appropriate:
-- creates a type to hold a list of varchars
CREATE OR REPLACE TYPE vc2_list_type as table of varchar2(4000);
-- converts a colon-delimited string of values to a list of varchars
CREATE OR REPLACE FUNCTION vc2_list(p_string in varchar2)
return vc2_list_type is
l_string long default p_string || ':';
l_data vc2_list_type := vc2_list_type();
n pls_integer;
begin
loop
exit when l_string is null;
n := instr(l_string, ':');
l_data.extend;
l_data(l_data.count) := ltrim(rtrim(substr(l_string, 1, n - 1)));
l_string := substr(l_string, n + 1);
end loop;
return l_data;
end vc2_list;
-- your WHERE clause
where risk_severity in(
select *
from the(select cast(vc2_list(:P2_RISK_SEVERITY) as vc2_list_type)
from dual))
...Hope this helps,
John -
Using a URL parameter in SQL Query
Newbie question...
I have been developing a dashboard application, and I have been using input bind variables in the SQL. That all works fine.
What I would like to do is to have a user go to a page via a URL with paramaters like this:
http://atlas:7777/pls/apex/f?p=112:1:9191429456552868531:::::P1_ITM_CD_PASSED:JMINV
where P1_ITM_CD_PASSED is the parameter and JMINV is the value.
Then, I want the SQL to execute using that:
select *
from itm
where itm_cd = ': P1_ITM_CD_PASSED'
I tried testing this on a page. Set up a report region, but it appears that the paramater is not making it to the SQL. "No Records Found".
Is there a simple example out there that anyone knows of? Maybe I am missing an item, computation, process, etc. to be able to utilize the paramater?
Thanks in advancevarad
Thanks for the reply. I did try that, and same results. It seems that the parameter is not getting bound to the variable, or it's getting flushed after the page loads. Here is what debug shows me:
P1_TEST
0.08: show report
0.10: determine column headings
0.10: activate sort
0.10: parse query as: CUSTOM
*0.11: binding: ":P1_ITM_CD_PASSED"="P1_ITM_CD_PASSED" value=""*
0.11: print column headings
0.11: rows loop: 15 row(s)
no data found
Edited by: jmcclain on May 13, 2010 4:01 PM -
Use the results of an SQL query to create another query
I am working on a bidding/allocation system using C# and MySQL, and I am currently having difficulty implementing the “post-allocation” mechanics of the system. Let me explain how it works, before introducing the code:
When the bids are made on the system, they all have the position 0, so the first thing the system does is order them according to priority.
(bid table)
In this case, 5 bidders are interested in what is in plot 15, but we have not assigned them a position yet.
(bid table)
The system then organises the bids according to the order in which they are going to processed.
The bids are then allocated, but unfortunately there are only 3 spaces in plot 15 that can be allocated. As a result, we use the priority listing to determine which bidder gets what.
(booking table)
At this stage, I can say that I am stuck, there are two things that I want to do, both of which involve reusing the results of the query at step 2.
(bid table)
The bidders that have their job allocated should see: their bid.status updated
from Queued to Allocated,
the bid.position should
be set to 0,
and their job_id should
be set to the booking they have been allocated (i.e. booking.id).
The bidders that have not had their jobs allocated should see: their bid.status remain
as Queued, and their bid.position should
be set to 0 in
preparation for the method to run again
The difficulty I am having is in stage 3, how do I determine which jobs have been allocated and which ones have not, and then run the necessary SQL queries in order to make the updates?
My code so far is as follows:
// STEP 1a - SELECT BIDS
string query =
"SELECT t1.operator_id, t1.datetime, t1.plot_id, t1.position, t2.market_access FROM bid t1 " +
"JOIN operator t2 ON t1.operator_id = t2.id WHERE t1.status='Queued' AND t1.postcode=@postcode " +
"ORDER BY t2.market_access ASC, t1.datetime ASC";
var bidList = new List<BidList>();
var cmd = new MySqlCommand(query, _connection);
cmd.Parameters.AddWithValue(("@postcode"), _plot);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
var item = new BidList
OperatorId = dataReader["operator_id"] + "",
PlotId = dataReader["plot_id"] + "",
Position = dataReader["position"] + "",
Datetime = dataReader["datetime"] + "",
MarketAccess = dataReader["market_access"] + "",
bidList.Add(item);
dataReader.Close();
// STEP 1b - SET PRIORITIES
for (var i = 0; i < bidList.Count; i++)
var position = i + 1;
bidList[i].Position = position.ToString();
query = "UPDATE bid SET position=@position WHERE status='Queued' AND postcode=@postcode AND operator_id=@operator_id;";
cmd = new MySqlCommand(query, _connection);
cmd.Parameters.AddWithValue(("@position"), position);
cmd.Parameters.AddWithValue(("@postcode"), _plot);
cmd.Parameters.AddWithValue(("@operator_id"), bidList[i].OperatorId);
cmd.ExecuteNonQuery();
dataReader.Close();
// STEP 2 - ALLOCATE JOBS ACCORDING TO PRIORITY
foreach (var t in bidList)
query = "SELECT operator_id, plot_id, status FROM booking " +
"WHERE status='open' AND postcode=@postcode AND operator_id='0'" +
"ORDER BY datetime ASC;" +
"UPDATE booking SET operator_id=@operator_id, status='Allocated' " +
"WHERE (plot_id=@plot_id AND operator_id='0' AND status='Open') LIMIT 1;";
cmd = new MySqlCommand(query, _connection);
cmd.Parameters.AddWithValue(("@operator_id"), t.OperatorId);
cmd.Parameters.AddWithValue(("@postcode"), _plot);
cmd.Parameters.AddWithValue(("@plot_id"), t.PlotId);
cmd.ExecuteNonQuery();
dataReader.Close();
// STEP 3
CloseConnection();I can't tell. When modifying row(s) you have to be able to uniquely be able to identify the row(s) in the database you want to modify. That is why I recommended the other day to use DataAdapter instead of the DataReader. You can with the
reader, but you need to unique identify the rows.
I can't tell from the limited amount of data you posted if in table 2 that there is only one row with the same operator id and plot id. It looks like in table 2 the 'id' number is unique. When working with a database with multiple tables you
need to be able to link tables together with primary keys (columns wit unique values). If the database isn't designed properly then it is impossible to do some operations. So you always have to make sure you design a database properly.
jdweng
When you say table 2 are you referring to the bid or booking table?
Here is the table structure for the bid table
Here is the table structure for the booking table
Hope it helps makes things clearer! -
How to use the result of a sql query for a max () function
Hi
I wrote a query on which i wrote
"select max(id) from users "
how can i use the returned value.
if i made the var name ="userid"
can it be userid.rows[0] or what.
thnx for any helpHi!
The result of this query will be the max ID of users' IDs.
Let say we have:
String sql="select max(users.id) from users";
Statement st = ctx.conn.createStatement();
ResultSet rs = st.executeQuery(sql);
rs.next();
So you can get the max Id in the following way:
int maxId=rs.getInt("id");
Regards,
Rossi -
Using CASE in a dynamic sql query
Hi,
I want to create a dynamic query using the CASE statement to replace the below 2 SQL statements:
+++++
select 'create or replace synonym '|| SYNONYM_NAME || ' for '||TABLE_OWNER||'.'||TABLE_NAME||'@'||SUBSTR(db_link,1,30)||' ;' FROM USER_SYNONYMS where db_link is not null;
select 'create or replace synonym '|| SYNONYM_NAME || ' for '||TABLE_OWNER||'.'||TABLE_NAME||' ;' FROM USER_SYNONYMS where db_link is null;
+++++
So that i have a single select query which will give the create synonym statements for all with/without db links
Using the CASE statement example like given below :
SELECT
FirstName, LastName,
Salary, DOB,
CASE Gender
WHEN 'M' THEN 'Male'
WHEN 'F' THEN 'Female'
END
FROM Employees
I am not getting how to write this CASE statement. Can someone guide me here?
Thanks,
KunwarKunwar wrote:
I am a Junior Oracle DBA. I would like to master SQL & PL/SQL concepts & tricks. Please guide me some books (apart from the oracle documentation links) which will improve my SQL & PL-SQL skills which are very weak right now. Personnally I started with the Oracle Class Training SQL&PL/SQL, then did a loooooooooooot of reading on [url http://asktom.oracle.com]AskTom (I even bought his book).
Also I tried (and I'm still trying) to answer to SQL/PLSQL problematic on this forum, then tried to see and learn from what other gave as answers.
I also spend and spent a lot of time in the Oracle Documentation. (I fear your "apart from the oracle documentation" to actually mean : apart reading the documentation)
Kunwar wrote:
TOAD alternative for create ddl statements for limited no. of objects
You need to learn to use dbms_metadata. I gave you an example, use the documentation and some self-testing to make it do what you need.
"Practice makes perfect"
And as an hint : To become a SQL & PL/SQL Master, you should first start by forgetting Toad : The real tool for learning is SQL*Plus.
Toad, as any tool, is only good in the hands of whom knows what they do and how things work. -
How to use an array in a SQL Query
Hi
I need to use an array of numbers such as a VARRAY or Associated Index Array so that I can do the following SQL:
select *
from *
where array is null or id is in array
So that if the array is empty it will return all the records, and if the array is not empty then it will return only the rows associated with the ids in the array.
Is this possible?
Regards,
Néstor BoscánActually, solution I posted returns all rows when VARRAY is empty, not when it is null. To return all rows when VARRAY is null, use:
SQL> select ename
2 from emp
3 where deptno in (select * from table(cast(sys.OdciNumberList(10,30) as sys.OdciNumberList)))
4 or sys.OdciNumberList(10,30) is null
5 /
ENAME
ALLEN
WARD
MARTIN
BLAKE
CLARK
KING
TURNER
JAMES
MILLER
9 rows selected.
SQL> select ename
2 from emp
3 where deptno in (select * from table(cast(null as sys.OdciNumberList)))
4 or null is null
5 /
ENAME
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
ENAME
JAMES
FORD
MILLER
14 rows selected.
SQL> SY. -
Not able to use date with time in sql query
Hi,
select a.contract_number,b.start_date,b.end_date,b.price_negotiated,b.attribute_category,b.attribute1,a.sts_code,a.contract_number_modifier,b.cle_id,b.creation_date
from OKC_K_HEADERS_ALL_B a,OKC_K_LINES_B b
where a.id = b.dnz_chr_id
and b.cle_id is not null
and a.contract_number_modifier is not null
and a.sts_code in ('ACTIVE','SIGNED','60 DAY HOLD','HOLD')
and b.creation_date between to_date('21-10-2013 9:19:48','DD-MM-YYYY HH24:MI:SS') and sysdate;
If I execute this query in toad it is giving me proper results.This query populates the results between the two date with time.
But I am facing issue when I am using this query in the procedure. The procedure is as below.
If I use the same query in the procedure I am getting wrong output.
CREATE OR REPLACE procedure xx_prog_upd_annualized_amt(errbuf out varchar2, retcode out varchar2)
as
cursor c1 (l_date in varchar2)is
select a.contract_number,b.start_date,b.end_date,b.price_negotiated,b.attribute_category,b.attribute1,a.sts_code,a.contract_number_modifier,b.cle_id
from OKC_K_HEADERS_ALL_B a,OKC_K_LINES_B b
where a.id = b.dnz_chr_id
and b.cle_id is not null
and a.contract_number_modifier is not null
and a.sts_code in ('ACTIVE','SIGNED','60 DAY HOLD','HOLD')
and b.creation_date between to_date(l_date,'DD-MM-YYYY HH24:MI:SS') and sysdate;
v_date varchar2(100);
v_total_days number;
v_annualized_amount number;
begin
begin
select max(fcr.actual_start_date) into v_date
from fnd_concurrent_programs_vl fcp
,fnd_concurrent_requests fcr
where fcp.concurrent_program_id = fcr.concurrent_program_id
and fcp.user_concurrent_program_name like 'Renewed Annualized Amount Updation';
exception
when others then
fnd_file.put_line(fnd_file.log,'Invalid date');
end;
fnd_file.put_line(fnd_file.output,v_date);
fnd_file.put_line(fnd_file.output,sysdate);
fnd_file.put_line(fnd_file.output,'***************Start of Program***************');
fnd_file.put_line(fnd_file.output,'***************Hi***************');
For i in c1(v_date) loop
SELECT
1
+ 30 * TRUNC (MONTHS_BETWEEN ( TO_DATE (i.end_date, 'DD-MON-YYYY'), TO_DATE (i.start_date, 'DD-MON-YYYY')))
+ LEAST (EXTRACT (DAY FROM TO_DATE (i.end_date, 'DD-MON-YYYY')), 30)
- LEAST (EXTRACT (DAY FROM TO_DATE (i.start_date, 'DD-MON-YYYY')), 30)
+ CASE
WHEN EXTRACT (DAY FROM TO_DATE (i.end_date, 'DD-MON-YYYY')) < EXTRACT (DAY FROM TO_DATE (i.start_date, 'DD-MON-YYYY')) THEN 30
ELSE 0
END
daysbetween into v_total_days
FROM dual;
fnd_file.put_line(fnd_file.output,i.contract_number);
fnd_file.put_line(fnd_file.output,v_total_days);
If v_total_days < 360 then
v_annualized_amount := (360*i.price_negotiated)/v_total_days;
update OKC_K_LINES_B
set attribute_category = 'Annualized Amount',attribute1 = v_annualized_amount
where cle_id = i.cle_id;
fnd_file.put_line(fnd_file.output,v_annualized_amount);
fnd_file.put_line(fnd_file.output,i.cle_id);
elsif v_total_days >= 360 then
update OKC_K_LINES_B
set attribute_category = 'Annualized Amount',attribute1 = i.price_negotiated
where cle_id = i.cle_id;
end if;
end loop;
commit;
fnd_file.put_line(fnd_file.output,'***************End of Program***************');
null;
end;SureshM wrote:
Hi Purvesh,
Apologize for not giving the sufficient information.
max(fcr.actual_start_date) = here I am getting date with time (for eg :9/4/2012 6:47:49 PM)
Datatype for this column is date.
This actual start date I am storing in varchar2 variable and then converting this value to date with time.
My requirement is to pick the rows between the two timestamps which I am unable to do in the procedure.
Regards
Suresh
YOu are losing the Time information while fetching the data into a VARCHAR2 variable. change the datatype of v_date to DATE and get rid of the TO_DATE logic in cursor and simply use v_date variable.
Message was edited by: PurveshK misread. -
Can the value of a drop down be used as part of an SQL query?
I am using JDeveloper11g to develop a web application that displays some data from a database table. To do so I created Business Component from Table (Entity) that represents one of the tables in the database. I then use a panelCollection component to display the data of the tables.
Assuming that the SQL of this entity is as follows:
SELECT test.field1 FROM test WHERE test.field2 = :MyVariableCan I somehow set :MyVariable to be equal to the value selected by a user from a selectOneChoice component?Hi,
Yes, you can. Check out setNamedWhereClauseParam method.
http://download.oracle.com/docs/cd/B31017_01/web.1013/b25947/bcquerying009.htm
For ex :
Re: add where clause dynamicaly
-Arun -
Using PreparedStatement to execute a SQL Query
hi All,
I am trying to use PreparedStatement to execute a Query in Java.
The Problem is that where Clause of that Query is dynamically formed as per
user inputs .
So , in this case will it help if I use PreparedStatement in place of Normal Statement ?
If Yes , then how to handle the Dynamic where clause of the Query ?
Thanks in Advance.
Regards,
ninadLet's say the user is providing a name, and you'r querying based on that name: PrepartedStatement ps = con.prepareStatement("select * from my_table where name = ?);
ps.setString(1, nameFromUser);
ResultSet rs = ps.executeQuery();
http://java.sun.com/developer/onlineTraining/Database/JDBC20Intro/
Maybe you are looking for
-
Get a waveform graph to stop plotting after a given time period
I am doing a research project looking at the effects of modifying visual feedback on a person's current force output. I have a waveform graph that plots the target force level they are trying to match (specified by me) and next to it a second plot sh
-
Error while trying to install AIA3.0 - Managed Server not found
Hi, I am trying to install AIA3.0 on soa suite 11g. I have installed soa suite 11g and started the weblogic server, soa_server1 and BAM server (these were 2 managed servers), also the Node manager is running. However on the screen "Soa Server Details
-
APAS 3.0 and Windows Live Mail program
How do I change the email client that Adobe Photoshop Album Starter 3.0 is using from Outlook express (old emailing program) to Windows Live mail (new emailing program)? When I change the 'edit, preferences, email, to "Hotmail", it goes to a web site
-
How to verify my apple id, how to verify my apple id
how to verify ,my apple id ?
-
PCR for overtime double on basic
Scenario = u201CWorkmen are paid overtime if they put extra effort of more the one hour. Overtime is calculated as double of the basic. The calculation rule will be : (2 * Overtime in hrs * Basic)/(8 * no of days in the