Using DECODE Function in SQL
I need to know if there is any way to use a range of values from
database and decode to certain text. I am able to do with one
value.
for example:
DECODE(column_name,'216767111','Unlimited',column_name)
above argument works with one value only. How about a range,
ex: 216767000 to 216767111. I need to use only SQL. No PL/SQL.
Kinldly need some body's help
Thanks
Munis
Which version of the database? If it's 8i+ then you can use
the CASE function
for example:
(CASE WHEN column_name between 216767000 and 216767111
THEN 'Unlimited' ELSE column_name END)
This won't work in PL/SQL because they're introducing a CASE
statement does soemthing different.
rgds, APCHello Andrew
Thank you for response. I am using 8i. 8.1.6. However using
CASE, I get inconsistent data type, ORA-00932: inconsistent
datatypes. I able to work it out with other response using
DECODE(sign(. Do you have any idea why i am getting this error.
If time permits, let me know
Similar Messages
-
How to use DECODE function in Exspression?
Hi,
Can we use DECODE in Expression?
I'm trying to use DECODE function but there is an error during the validation. But when i validate the mapping, it is successfully compiled but it is failed during deployment.
But if I use CASE instead of DECODE, it works fine.
Can we use DECODE in OWB???
Thanks
RajHi,
In OWB 10gR2, if your are using only one DECODE in an expression, it's working. The package will compile when deploying the mapping. OWB will replace the DECODE by a CASE.
But when you are using nested decode in an expression ( for example : decode(col1, 1, 'M', decode(col2, 'Madame', 'Mme', null)) ) only the first one is replaced by a case at deployment.
In ROW_BASED mode, text of the expression is used outside of an sql statement and deployment will fails with "PLS-00204: function or pseudo-column 'DECODE' may be used inside a SQL statement only."
If operating mode for the mapping is set to SET_BASED, it's working because the expression is used in an sql statement.
I have logged a SR in metalink for this issue and a bug is opened (bug 5414112).
But I agree with you, it's better to use case statement.
Bernard -
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>
) -
Using decode function without negative values
Hi friends
I am using oracle 11g
I have at doubt regarding the following.
create table Device(Did char(20),Dname char(20),Datetime char(40),Val char(20));
insert into Device values('1','ABC','06/13/2012 18:00','400');
insert into Device values('1','abc','06/13/2012 18:05','600');
insert into Device values('1','abc','06/13/2012 18:55','600');
insert into Device values('1','abc','06/13/2012 19:00','-32768');
insert into Device values('1','abc','06/13/2012 19:05','800');
insert into Device values('1','abc','06/13/2012 19:10','600');
insert into Device values('1','abc','06/13/2012 19:15','900');
insert into Device values('1','abc','06/13/2012 19:55','1100');
insert into Device values('1','abc','06/13/2012 20:00','-32768');
insert into Device values('1','abc','06/13/2012 20:05','-32768');
Like this I am inserting data into table for every 5 minutes Here i need the result like
output:
Dname 18:00 19:00 20:00
abc 400 -32768 -32768
to retrieve this result i am using decode function
SELECT Dname,
MAX(DECODE ( rn , 1,val )) h1,
MAX(DECODE ( rn , 2, val )) h2,
FROM
(SELECT Dname,Datetime,row_number() OVER
(partition by Dname order by datetime asc) rn FROM Device
where substr(datetime,15,2)='00' group by Dname.
According to above data expected result is
Dname 18:00 19:00 20:00
abc 400 600(or)800 1100
This means I dont want to display negative values instead of that values i want to show previous or next value.
Edited by: 913672 on Jul 2, 2012 3:44 AMAre you looking for something like this?
select * from
select dname,
datetime,
val,
lag(val) over (partition by upper(dname) order by datetime) prev_val,
lead(val) over (partition by upper(dname) order by datetime) next_val,
case when nvl(val,0)<0 and lag(val) over (partition by upper(dname) order by datetime) >0 then
lag(val) over (partition by upper(dname) order by datetime)
else
lead(val) over (partition by upper(dname) order by datetime)
end gt0_val
from device
order by datetime
where substr(datetime,15,2)='00';Please take a look at the result_column gt0_val.
Edited by: hm on 02.07.2012 04:06 -
Hello Friends,
I have a query that has different columns and I am not sure what the data type of each column is ...
I want to use decode function which displays the following if the value of the column is like this ..
if the value of column is -714E ie -700000000000000 then display as .A
if the value of column is -814E ie -800000000000000 then display as .B
NOTE ; don't know which column is having the value - and i don't know the data type of the column is ..
got to use the decode function for all the columns selected ..
I want to use decode function pls let me know how to write for this kind of requirement.
appreciate your help in this rgds.
thanks/kumarDear Sir / Madam,
Thanks for your understanding.
Right now I am facing a unique problem.
I am using decode function in a select statement. The columns are dynamic some columns are of type number and some are varchar datatypes. I want to apply decode function for every column irrespective of datatype.
What i am finding difficult is if the column is a number datatype , the decode funciton is working good but if the column datatype is varchar or char datatype then i am getting ..
here's the decode function..
decode (CHAI.EVNDRIVE,
-800000000000000,'.A',
-700000000000000, '.B',
-600000000000000 ,'.C',
-500000000000000 , '.D',
-400000000000000 , '.E',
-300000000000000 , '.F',
-200000000000000, '.G',
-100000000000000 , '.H',
-1000000000, '.R' ,CHAI.EVNDRIVE ) EVNDRIVE
report error:
ORA-01722: invalid number
pls let me know how to over come this kind of scenario.
is their a way to find whether the column datatype is number or char , so that i can check the column datatype before the decode funciton is applied ..
thanks ..
kumar -
Problem using extract function (PL/SQL) with "&#34"
Hi,
When I use extract function (PL/SQL), it does not transform well """. Insted of returning ' " ' , it returns ' " '.
I know this works changing the code replacing xml.extract for SELECT extractvalue(xml,'//A/text()') into v from dual;
But Is there another way to do this using PL/SQL? any patch, option..?
RegardsHad to use my website to demonstrate the code...
As said, whatever I try here the code gets automatically converted...
See for answer on your question: http://www.liberidu.com/blog/?p=635 -
Problem using DECODE() function with a Query of Queries
I
posted
on my blog about an issue I was having trying to use the PL/SQL
DECODE() function with a Coldfusion Query of Queries. This function
works fine when you query a database for information. However, when
you query another query, it seems that CF doesn't recognize it. I
got errors stating that it found a left parenthesis where it
expected a FROM key word. Here is a simplified version of what I am
trying to do:
quote:
<!--- Simulated query; similar to what I was calling from
my database --->
<cfscript>
qOriginal = queryNew("Name,Email,CountryCode",
"VarChar,VarChar,VarChar");
newRow = queryAddRow(qOriginal, 5);
querySetCell(qOriginal, "Name", "Joe", 1);
querySetCell(qOriginal, "Email", "[email protected]", 1);
querySetCell(qOriginal, "CountryCode", "AMER", 1);
querySetCell(qOriginal, "Name", "Sally", 2);
querySetCell(qOriginal, "Email", "[email protected]", 2);
querySetCell(qOriginal, "CountryCode", "AMER", 2);
querySetCell(qOriginal, "Name", "Bob", 3);
querySetCell(qOriginal, "Email", "[email protected]", 3);
querySetCell(qOriginal, "CountryCode", "ASIA", 3);
querySetCell(qOriginal, "Name", "Mary", 4);
querySetCell(qOriginal, "Email", "[email protected]", 4);
querySetCell(qOriginal, "CountryCode", "EURO", 4);
querySetCell(qOriginal, "Name", "John", 5);
querySetCell(qOriginal, "Email", "[email protected]", 5);
querySetCell(qOriginal, "CountryCode", "EURO", 5);
</cfscript>
<cfquery name="qCountries" dbtype="query">
SELECT DISTINCT(CountryCode) AS CountryCode,
DECODE(states, "AMER", "North America & Canada",
"EURO", "Europe & Africa", "ASIA", "Japan &
Asia","") CountryName
FROM qOriginal
ORDER BY CountryCode
</cfquery>
<cfdump var="#qCountries#">
<!--- ========== END OF CODE ========== --->
So running this returned the following error:
Query Of Queries syntax error.
Encountered "(. Incorrect Select Statement, Expecting a
'FROM', but encountered '(' instead, A select statement should have
a 'FROM' construct.
Does anybody know why this doesn't work? Is it just not
supported? Please note that I have also tried to use the CASE()
function instead of DECODE() and that resulted in basically the
same error. For now I an looping over my distinct query with a
switch statement and manually loading a new query with the data how
I want it. But it would be a lot cleaner and less code to have the
DECODE() to work. Thx!DECODE() is an Oracle function, not generic SQL. Q-of-Q is a
very limited subset of SQL and lacks many functions and clauses
available in standard SQL, especially what you may be used to using
in your particular RDBMS.
See
Query
of Queries user guide
Phil -
Using DECODE Function to change data
I am trying to use the Decode function in a SQL statement to find a field that has a specific type, and when it finds that type, I want to blank out the results in a different field.
For example:
DECODE(ADDR_TYPE,'HOME',PHONE='') HOME_PHONEsomething like:
SQL> with t as
2 (select 219 id,
3 'BUS' addr_type,
4 '505-555-5555' phone
5 from dual
6 union
7 select 219 id,
8 'HOME' addr_type,
9 null phone
10 from dual
11 union
12 select 220 id,
13 'BUS' addr_type,
14 '101-111-1111' phone
15 from dual
16 union
17 select 220 id,
18 'HOME' addr_type,
19 null phone
20 from dual
21 union
22 select 223 id,
23 'BUS' addr_type,
24 '202-222-2222' phone
25 from dual
26 union
27 select 224 id,
28 'HOME' addr_type,
29 '303-333-3333' phone
30 from dual
31 union
32 select 225 id,
33 'BUS' addr_type,
34 null phone
35 from dual
36 union
37 select 226 id,
38 'HOME' addr_type,
39 null phone
40 from dual)
41 select a.id,
42 a.addr_type,
43 decode(a.addr_type,'BUS',phone,null) phone
44 from (select id, addr_type, phone,
45 row_number() over (partition by id order by id, decode(addr_type,'BUS',1,2)) rn
46 from t) a
47 where a.rn = 1;
ID ADDR PHONE
219 BUS 505-555-5555
220 BUS 101-111-1111
223 BUS 202-222-2222
224 HOME
225 BUS
226 HOME
6 rows selected.
SQL> -
How to use Decode Function in Webi / Designer - BOE XI 3.1
Hi All,
I have a SQL query which needs to include in the webi report.
Below is the query :
SELECT
SECURITY.SEC_CUSIP_NO "CUSIP",
SECURITY.STY_SEC_TY_CD "SECURITY TYPE",
SECURITY.SEC_DERIVED_DESC_TX "SECURITY DESCRIPTION",
SECURITY.sec_dep_teleg_de "FED DESCRIPTION",
SEC_STND_PR "STANDARD/FACTORED PRICE",
SEC_STND_PR_EFF_DT "STANDARD/FACTORED PRICE Date",
SECURITY.SEC_YIELD_PR "YIELD PRICE",
SECURITY.SEC_YIELD_PR_DT "YIELD RICE EFFECTIVE DATE",
STND_PR_VND_VENDOR_CD "PRICE SOURCE",
SEC_MATURITY_DT "MATURITY DATE",
SEC_ISSUE_DT "ISSUE DATE",
CASE WHEN SECURITY.STY_SEC_TY_CD IN ('BA','CD','CDD','CDE','CDM','CDV','CP','CPD') THEN
(position.PSN_AVAIL_PAR_VL + position.PSN_COLLAT_PAR_VL) * (SECURITY.SEC_STND_PR) / 100
ELSE
(position.PSN_AVAIL_PAR_VL + position.PSN_COLLAT_PAR_VL) * ( ( SECURITY.SEC_YIELD_PR * DECODE (SECURITY.SEC_PRIN_FT, 0, 1, SECURITY.SEC_PRIN_FT))) / 100
* DECODE(SECURITY.STY_SEC_TY_CD, 'AMP', DECODE(NVL(SECURITY.SEC_MULTIPLIER_UNIT_VL,0), 0, 1, SECURITY.SEC_MULTIPLIER_UNIT_VL), 'MMP', DECODE(NVL(SECURITY.SEC_MULTIPLIER_UNIT_VL,0), 0, 1, SECURITY.SEC_MULTIPLIER_UNIT_VL), 'AMPT', DECODE(NVL(SECURITY.SEC_MULTIPLIER_UNIT_VL,0), 0, 1, SECURITY.SEC_MULTIPLIER_UNIT_VL), 1 )
END
) "MARKET VALUE"
FROM SECURITY SECURITY
, position position
WHERE STND_PR_VND_VENDOR_CD = 'VT'
AND SEC_MATURITY_DT > SYSDATE-1
and SECURITY.sec_sys_id=position.sec_sys_id
I could create a report which has selected objects and defined where condition from the above query. I have also created a variable for 'when' & 'then' condition but stuck at else part which contains 'DECODE' function.
Please suggestions how to write the same at the report or designer level.
Thanks,
Rameez ShaikhHi Rameez,
Looking at the query you can create the object directly in the universe, either create two objects one for inner decode and use it in outer case logic. In report it is nothing but nested if logic. For eg. If(a=b;1;(if(a=c;2;3))
Thanks
Gaurav -
How to use decode function in oracle apex 3.2.1
Hello Friends,
how to use decode
var_decode := 'decode'||'('|| var1 ||','|| -800000000000000||','||'.A'||','||
appreciate your help.
regards/kumar
Edited by: kumar73 on Apr 23, 2010 12:25 PM
Edited by: kumar73 on Apr 23, 2010 12:27 PMHey just on this particular point, there's a handy PL/SQL method for escaping quotation characters which may reduce the complexity of the string.
For example, if I had a string:
I can't understand why quoting my 'quote' characters never seems to "work"!and I wanted to pass that into a variable, I could do this:
vc_foo:= 'I can''t understand why my ''quote'' characters never seems to "work"!';or I could use the q function, whereby you enclose your string within a quote delimiter of your choice, like so:
vc_foo:= q'^I can't understand why quoting my 'quote' characters never seems to "work"!^';
note: I used the caret (^) character by convention but any valid character will do
...all of which leaves your original string more or less unadulterated.
I find this particularly useful for generating dynamic SQL and dynamic PL/SQL, as it leave the query looking a tad more readable, although if you are chaining together multiple strings with double-pipes, it can make it a little muddier. I find it particularly useful if I'm going to deal with string data from, for example, a field with Irish-derived surnames such as "O'Reilly"...
Give it a go! -
Using User function in SQL*Loader
Hi, I have created the following control file. I am using DIRECT path insert. I am using a function to retrieve the column system_date. However, when I am running sql*loader, the fields system_date and load_date are loaded with null value.
OPTIONS (ERRORS=999999999, DIRECT=TRUE, ROWS=100000, SKIP=1)
LOAD DATA
INFILE 'Z:\xx.csv'
APPEND
PRESERVE BLANKS
INTO TABLE TB_RAW_DATA
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
REFERENCE_NUMBER,
SYSTEM_DATE "pkg_ken_utility.Fn_ken_get_param_value('SYSTEM_DATE','SYSTEM_DATE')",
LOAD_DATE "SYSDATE"
)No,
You can not call PL/SQL functions in DIRECT PATH mode, also this is documented, so you should not need to ask.
Sybrand Bakker
Senior Oracle DBA -
Using cursor function in sql statement
hi all
can anyone plss explain why and when we will use cursor function in a sql statement like this and what is the difference while executing this sql statement with cursor function in comparison of a simple sql statement----
select
department_name,
cursor (
select last_name
from employees e
where e.department_id = d.department_id
order by last_name
) the_employees
from departments d
thnx in advanceRTFM
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/sqloperations.htm#sthref1452
Cheers
Sarma. -
Order by clause using decode function
Hi everybody,
i need below order in my report.
Connecticut
greenwich
stamford
bridgeport
New York
NYC
wrestcher
byram
Georgia
atlanta
athens
oconny
first i need above order in my view out put.
so in order by clause i used first decode function for State ordering
and in second decode function for city ordering.
i do not need order by ascending or descending.
so pls anybody can help me.
any help is greatly appreciated.
thanks.add asc after the decode. default is desc
-
Regardin handling exception in a function, while using that function in sql
Hi gurus,
I have a question regarding logging exceptions while using functions.
I wrote a separate package to handle errors, where i have a procedure.
In this proc i'm logging my error into a table and then raise the error to the front end.
Ex:
proc_log_and_raise -- this proc... inserts my error into a table and then raisenow i included this error procedure in all functions and procedures.
consider an example with a sample procedure and function.
function func_1(( v_var varchar2) return varchar2 is
begin
select column2
from table2
where col1 = v_var;
exception
when others then
proc_log_and_raise;
end;
procedure proc_1( v_var varchar2) is
begin
select func_1(v_var) -- error occurs here..
from table_a
where col1 = v_var;
exception
when others then
proc_log_and_raise;
end; now i do
exec proc_1( v_var );but now my problem is, when an error occurs in func_1, i'm getting an error with DML operation ( as we are inserting into error table)
ORA-14551: cannot perform a DML operation inside a query.
so what i want to do is, log both function and procedure where error occured.
So is there any other better way, we can write our exception handling, so that i can log error and use function in a select statement.
thank you.I changed my procedure a little, to make it simple.
FUNCTION PKG_WEEKLY.FUNC_1
RETURN NUMBER IS
exc exception;
BEGIN
raise exc;
RETURN v_provr_rcoupt;
EXCEPTION
when exc then
PKG.PKG_ERROR.USP_LOG_AND_RAISE(
'batch_1',
'func_1',
SQLCODE,
DBMS_UTILITY.FORMAT_ERROR_STACK || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE());
END FUNC_1;
PROCEDURE PKG_WEEKLY.PROC_1(
cur_details OUT sys_refcursor) IS
BEGIN
OPEN cur_details FOR
SELECT NVL(PKG.PKG_WEEKLY.FUNC_1,0)) FROM DUAL;
EXCEPTION
WHEN OTHERS THEN
REPORT_APP_PKG.PKG_REPORT_ERROR.USP_LOG_AND_RAISE(
'batch_1',
'PROC_1',
SQLCODE,
DBMS_UTILITY.FORMAT_ERROR_STACK || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE());
END PROC_1; Now i execute it.
exec PKG_WEEKLY.PROC_1(:cursor); Error logged into the table:
242 batch_1 func_1 ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at "REPORT_APP_PKG.PKG_REPORT_WEEKLY_CAO", line 230
04/14/2009 16:09:25
ERRORS displayed to the front end:
ORA-20156: ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at "PKG.PKG_WEEKLY", line 230
ORA-06512: at "PKG.PKG_ERROR", line 48
ORA-06512: at "PKG.PKG_ERROR", line 226
ORA-06512: at "PKG.PKG_WEEKLY", line 261
thank you -
Using XML functions in SQL Developer
Hi,
I'm using OSD 1.5.3 on a WinXP machine. I love OSD and use it every day! But I think i found a little bug. When you use some Oracle XML functions like (XMLELEMENTS and XMLAGG) in your query (these functions return CLOB values) it hangs OSD.
For Example:
SELECT XMLELEMENT("Relation",
XMLELEMENT("Name", 'Dennis'),
XMLELEMENT("DateOfBirth", '09/28/1975')
) as Relation
FROM DUAL;
Are there some parameters I can set to prevent this, or is this a bug?
Kind Regards,
D.Your query works fine for me from SQL Dev 1.5.3 (JDK 1.6.0_06), using either a JDBC or TNS connection (Oracle Client 9.2) to a 10.2.0.3 DB. Another thing which I have no idea if it is relevant (someone else may be able to say) is the following line from Help > About > Properties:
oracle.xdkjava.compatibility.version 9.0.4
Given that it works fine over TNS connections from SQL*Plus and PL/SQL Developer, I would assume that it is something related to your SQL Developer setup, unless you are using a different version of the Oracle client for these tools.
theFurryOne
Maybe you are looking for
-
Lost music files after upgrading to itunes 7
Hi, can someone please confirm whether or not my music files have been physically deleted from my computer after upgrading to itunes 7. Many of the songs in my playlist, including MOST of the songs purchased through itunes come up with the error that
-
Can I Boot my PB from a Firewire 800 External HD?
I'm a going to buy a portable external HD for my mirror (clone) back-up drive. I can buy either a Firewire 400 ("Combo case") or 800 ("Triple case") HD. My inclination is to buy the Firewire 800 ("Triple case") drive as it will be more useful in the
-
I need a help. The environment, SharePoint and Project Server 2013 and SQL Server 2012, running on Windows Server 2008. Editing Details Web Part in a Schedule PDP Page, saved invalid Project Web App URL. After that, can display the Project Informatio
-
folks i'm trying to upgrade the sdm on my 1841 via the update tool in the sdm but when trying to load onto the router the upload failed after it had removed the old sdm so now i can't get onto the router anyone any suggestions how i can recover this?
-
Unlocking security mode on wireless router
I'm trying to unlock the security mode on the wireless router because I'm having a hard time adding a laptop to my wireless setting. Can anyone help?