Case Statement in Select Statement - Oracle 8.0.6
I am trying to do the following, but am getting error -
"FROM keyword not found where expected"
select s.item, s.dest, s.qty ,
case when s.dest = 'x'
then (sales - returns)
else 0
end
from table1 s
Is this an error or is it because of the version of Oracle?
As I recall, CASe was not supported until 8.1. So, you need to use decode instead.
SELECT s.item, s.dest, s.qty ,
DECODE(s.dest,'x',s.sales - s.returns,0)
from table1 sTTFN
John
Similar Messages
-
Difference between "print" statements and "select" statements , TSQL
What is the difference between "print" statements and "select" statements when it omces to debugging and watching varibles in the stored procs .....
SELECT statement is part of the ANSI SQL language.
PRINT command is not part of the SQL language, it is used for debugging in T-SQL.
BOL:" Returns a user-defined message to the client.
A message string can be up to 8,000 characters long if it is a non-Unicode string, and 4,000 characters long if it is a Unicode string. Longer strings are truncated. The
varchar(max) and nvarchar(max) data types are truncated to data types that are no larger than
varchar(8000) and nvarchar(4000).
RAISERROR can also be used to return messages. RAISERROR has these advantages over PRINT:
RAISERROR supports substituting arguments into an error message string using a mechanism modeled on the printf function of the C language standard library.
RAISERROR can specify a unique error number, a severity, and a state code in addition to the text message.
RAISERROR can be used to return user-defined messages created using the sp_addmessage system stored procedure."
LINK: http://technet.microsoft.com/en-us/library/ms176047.aspx
The SSMS (client software) returns SELECT output to Results and PRINT output to Messages.
The SQLCMD -o (output file) option captures all outputs into one file mixed.
Kalman Toth Database & OLAP Architect
T-SQL Scripts at sqlusa.com
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
Case sensitve in selection statement
Hi All
I like to write a select statement which is able to get the values irrespective of case sesitive
ie
select * from table_name where column_name like('%sun%')
selection of columns should happen even the column name is '%SUN%' or '%Sun%' ie '%sun%' should not be case sensitive....Can anyone suggest me query for this
Note: the query needs to work in oracel server. Also changing the session ie alter session set NLS_SORT=BINARY_CI ;
alter session set NLS_COMP=LINGUISTIC; cannot be done.
So please help me to get the selection purely through query
With thanks and regards
AnoopUse LOWER or UPPER,
so, for example:
lower(column_name) like '%sun%'
-- OR
upper(column_name) like '%SUN%' -
Pass list of values in an array to the IN statement of SELECT in Oracle 10g
Hi,
This is what I have done so far...
I have loaded the main array array_number_1 using BULK Collect. Within the loop I am filtering the data from this array and writing to another array array_number_2.
I want to use the values from array_number_2 in the SELECT statement.
Eg: SELECT sum(x_amount) charges
FROM x_table
WHERE id IN (array_number_2).
Could you provide a solution to this preferrably with an example.
thanksI'm not entirely following you, Visakh, but I have a SQL Task setup in which I have an expression that makes a call to a db2 database such as the abbreviated set example below. The list of IDs in the IN statement must come from another SQL Server
database. In the past I have gotten the list of IDs, put them in a recordset and then put that in a for loop to iterate and make one call to db2 for each and every ID. The single ID example can literally take days to run for 100,000 IDs.
Therefore, I want to pull the entire set of results back at one time via a single (or at least fewer calls than there are IDs) DB2 call using 'in' instead. Maybe I am overlooking something but I don't quite see how your example will get me where
I want to go.
Set Example
SELECT
A,
B
FROM
Table 1,
Table 2,
WHERE
Joins
AND PRSNEUP.ID in ( This is where I want a list of IDs )
Single ID Example
SELECT A,
B
FROM
Table 1, Table 2,
WHERE
Joins AND PRSNEUP.ID = ( VariableContainingASingleID -
If statement in select statement alias
I have the following select statement. It has the alias Survivors, Deaths and "All Cases". Is it posible to use :P_LANGUAGE variable to say that -- IF :P_LANGUAGE = FRENCH THEN alias are Survivants for survivors, Décès for Deaths, Tous_les_cas for All Cases. Please advise
SELECT ALL T_NTR_MULTIBAR.CAT, T_NTR_MULTIBAR.NUM_CASES_LEFTBAR AS Survivors,
T_NTR_MULTIBAR.NUM_CASES_MIDDLEBAR AS Deaths, T_NTR_MULTIBAR.NUM_CASES_RIGHTBAR AS "All Cases"
FROM T_NTR_MULTIBAR
WHERE INSTANCE_NUM = :P_INSTANCENUM
order by ORDERSYou may not be able to add this condition inside the SQL Statement. But you can add this condition outside the statement, if you're using PL/SQL...
IF :p_language = french THEN
SELECT ALL t_ntr_multibar.cat,
t_ntr_multibar.num_cases_leftbar AS survivors,
t_ntr_multibar.num_cases_middlebar AS deaths,
t_ntr_multibar.num_cases_rightbar AS "All Cases"
ELSE
END IF; -
Update Statement using SELECT statement
The following select query return 1 record to me
[code]
select deptno , dname, empno , max_date, max(v_num)
from (select d.deptno , d.dname , e.empno ,max (ver_date) over(partition by d.id ,d.no) max_date ,v_num
from emp e ,dept d
where e.deptno=d.deptno and e.dname = d.dname and e.empno=1 and d.deptno =3 )
group by deptno , dname, empno , max_date
[/code]
Now I need to update the above value to the emp table itself
In emp table for the empno=1 I need to update the columns mx_Date and v_num columns with the above last 2 columns in the select statement (max_date, max(v_num) )
How can I write the update statement for this.
Thank YouSomething like this
merge into emp e1
using (
select deptno
, dname
, empno
, max_date
, max(v_num) v_num
from (
select d.deptno
, d.dname
, e.empno
, max (ver_date) over(partition by d.id , d.no) max_date
, v_num
from emp e
, dept d
where e.deptno = d.deptno
and e.dname = d.dname
and e.empno = 1
and d.deptno = 3
group
by deptno
, dname
, empno
, max_date
) e2
on (
e1.empno = e2.empno
when matched then
update set e1.mx_date = e2.max_date,
e1.v_num = e2.v_num -
Doubt about Select statement.
Hi folks!!
I have a few doubts about the select statements, it may be a silly things but its useful for me.
what is difference between below statment.
1)SELECT * FROM TABLE.
2)SELECT SINGLE * FROM TABLE
3)SELECT SINGLE FROM TABLE.
Hope i will get answer,thanks in advance.
Regards
Richie..Hi,
try this and if possible use sap help.i mean place the cursor on select and press F1.
Types of select statements:
1. select * from ztxlfa1 into table it.
This is simple select statement to fetch all the data of db table into internal table it.
2. select * from ztxlfa1 into table it where lifnr between 'V2' and 'V5'.
Thisis using where condition between v2 and v5.
4. select * from ztxlfa1 where land1 = 'DE'. "row goes into default table work Area
5. select lifnr land1 from ztxlfa1
into corresponding fields of it "notice 'table' is omitted
where land1 = 'DE'.
append it.
endselect.
Now data will go into work area. and then u will add it to internal table by
append statement.
6. Table 13.2 contains a list of the various forms of select as it is used with internal tables and their relative efficiency. They are in descending order of most-to-least efficient.
Table 13.2 Various Forms of SELECT when Filling an Internal Table
Statement(s) Writes To
select into table it Body
select into corresponding fields of table it Body
select into it Header line
select into corresponding fields of it Header line
7. SELECT VBRK~VBELN
VBRK~VKORG
VBRK~FKDAT
VBRK~NETWR
VBRK~WAERK
TVKOT~VTEXT
T001~BUKRS
T001~BUTXT
INTO CORRESPONDING FIELDS OF TABLE IT_FINAL
FROM VBRK
INNER JOIN TVKOT ON VBRKVKORG = TVKOTVKORG
INNER JOIN T001 ON VBRKBUKRS = T001BUKRS
WHERE VBELN IN DOCNUM AND VBRK~FKSTO = ''
AND VBRK~FKDAT in date.
Select statement using inner joins for vbrk and t001 and tvkot table for this case based on the conditions
8. SELECT T001W~NAME1 INTO TABLE IT1_T001W
FROM T001W INNER JOIN EKPO ON T001WWERKS = EKPOWERKS
WHERE EKPO~EBELN = PURORD.
here selecting a single field into table it1_t001winner join on ekpo.
9. SELECT BUKRS LIFNR EBELN FROM EKKO INTO CORRESPONDING FIELDS OF IT_EKKO WHERE EBELN IN P_O_NO.
ENDSELECT.
SELECT BUTXT FROM T001 INTO IT_T001 FOR ALL ENTRIES IN IT_EKKO WHERE BUKRS = IT_EKKO-BUKRS.
ENDSELECT.
APPEND IT_T001.
here I am using for all entries statement with select statement. Both joins and for all entries used to fetch the data on condition but for all entries is the best one.
10. SELECT AVBELN BVTEXT AFKDAT CBUTXT ANETWR AWAERK INTO TABLE ITAB
FROM VBRK AS A
INNER JOIN TVKOT AS B ON
AVKORG EQ BVKORG
INNER JOIN T001 AS C ON
ABUKRS EQ CBUKRS
WHERE AVBELN IN BDOCU AND AFKSTO EQ ' ' AND B~SPRAS EQ
SY-LANGU
AND AFKDAT IN BDATE AND AVBELN EQ ANY ( SELECT VBELN FROM
VBRP WHERE VBRP~MATNR EQ ITEMS ).
Here we are using sub query in inner join specified in brackets.
Thanks,
chandu. -
Performance Issue in Select Statement (For All Entries)
Hello,
I have a report where i have two select statement
First Select Statement:
Select A B C P Q R
from T1 into Table it_t1
where ....
Internal Table it_t1 is populated with 359801 entries through this select statement.
Second Select Statement:
Select A B C X Y Z
from T2 in it_t2 For All Entries in it_t1
where A eq it_t1-A
and B eq it_t1-B
and C eq it_t1-C
Now Table T2 contains more than 10 lac records and at the end of select statement it_t2 is populated with 844003 but it takes a lot of time (15 -20 min) to execute second select statement.
Can this code be optimized?
Also i have created respective indexes on table T1 and T2 for the fields in Where Condition.
Regards,If you have completed all the steps mentioned by others, in the above thread, and still you are facing issues then,.....
Use a Select within Select.
First Select Statement:
Select A B C P Q R package size 5000
from T1 into Table it_t1
where ....
Second Select Statement:
Select A B C X Y Z
from T2 in it_t2 For All Entries in it_t1
where A eq it_t1-A
and B eq it_t1-B
and C eq it_t1-C
do processing........
endselect
This way, while using for all entries on T2, your it_t1, will have limited number of entries and thus the 2nd select will be faster.
Thanks,
Juwin -
Count(*) function in select statement having group by condition
Hi
I would like to use count(*) in select statement having group by clause. say for example there is a state with a number of cities listed. I would like to get the count of cities for each state.
the sql stement is grouped by state and it is joined with 5 more tables.
Thanks
ps: ignore the previous postAssuming there is one record per city per state, then
SELECT state,count(*)
FROM state_tbl
GROUP BY stateWill get one record per state with the number of cities in each state. If you want to join that result set to other tables you need to either create a view with that statement or use an in-line view viz.
SELECT c.cust_name,c.state,s.num_cities
FROM customers c,
(SELECT state,count(*) num_cities
FROM state_tbl
GROUP BY state) s
WHERE c.state = s.stateTTFN
John -
Need to create a transaction for multiple select statements?
Hello,
I am a newbie and have a question about database transaction, e.g. whether/not to enclose multiple select statements (and select statements only) into a transaction.
My database is set to transaction isolation level 2: REPEATABLE READ, where dirty read & non-repeatable read are not allowed, only phantom read is allowed.
Now, in my code I have a number of methods that only contain select statements only. Since they are merely select statements, which don't do any modifications to the data, I am not sure if I am supposed to enclose them into a transaction.
However, if I don't put them into a transaction will the transaction isolation level takes into effect automatically when another user is modifying the data that I am reading? In other words, I need to make sure the select statements will never do either dirty read or non-repeatable read. But I am not sure if it is necessary to enclose multiple select statements in a transaction, since I believe putting the select statements into a transaction will put some locks to the data being read which may reduce the concurrency of my application.
Any help/advice would be very much appreciated.
DuaneYou might want to try asking this on a forum that specific to your database. I suspect the answer can vary depending on the database and probably requires in depth knowledge of what the database does.
-
Convert sql select statement to oracle
Hi All,
Can anyone help me converting this Sql select statement to oracle ....
-----------------------------------------Query--------------------------------------------------------------
select emp_master.emp_code ,
emp_master.dept_cd ,
attendance_master.daily_attn_code ,
attendance_master.linked_column ,
case when location.payroll_status <> 'N' and eDocsNetEmployeesLeave.StartDate < dateadd(mm, 1 , convert(smalldatetime, datename(yy ,location.next_pay_date) + '/'+ datename(mm ,location.next_pay_date)+ '/01'))
then
dateadd(mm, 1 , convert(smalldatetime, datename(yy ,location.next_pay_date) + '/'+ datename(mm ,location.next_pay_date)+ '/01'))
when eDocsNetEmployeesLeave.StartDate < convert(smalldatetime, datename(yy ,location.next_pay_date) + '/'+ datename(mm ,location.next_pay_date)+ '/01')
then convert(smalldatetime, datename(yy ,location.next_pay_date) + '/'+ datename(mm ,location.next_pay_date)+ '/01') else eDocsNetEmployeesLeaveDetails.StartDate
end ,
eDocsNetEmployeesLeaveDetails.NoOfDays,
case when eDocsNetEmployeesLeave.StartDate > location.next_pay_date
then convert(datetime , convert(varchar, dateadd(ss,-1, dateadd(mm, 1, convert(datetime , datename(yy,eDocsNetEmployeesLeave.StartDate)+ '/' + datename(mm,eDocsNetEmployeesLeave.StartDate)+ '/01') )),106) )
else
case when location.payroll_status <> 'N'
then dateadd(mm,1,location.next_pay_date)
else location.next_pay_date
end
end as PaymentDate ,
isnull(grade_master.leave_type,'C') ,
eDocsNetEmployeesLeave.StartDate ,
eDocsNetEmployeesLeaveDetails.LeaveType
from eDocsNetEmployeesLeave ,
eDocsNetEmployeesLeaveDetails ,
eDocsNetLeaveTypes ,
emp_master ,
grade_master ,
attendance_master ,
location
where eDocsNetEmployeesLeaveDetails.RequestID = eDocsNetEmployeesLeave.RequestID and
eDocsNetEmployeesLeave.EmployeeID = emp_master.emp_code and
eDocsNetEmployeesLeaveDetails.LeaveType = eDocsNetLeaveTypes.LeaveTypeID and
eDocsNetLeaveTypes.loc_cd = emp_master.loc_cd and
location.loc_cd = emp_master.loc_cd and
attendance_master.loc_cd = emp_master.loc_cd and
attendance_master.linked_column = eDocsNetLeaveTypes.LinkedAttendance and
grade_master.loc_cd = emp_master.loc_cd and
grade_master.grade_cd = emp_master.grade_cd and
eDocsNetEmployeesLeaveDetails.RequestID = @RequestID
order by eDocsNetEmployeesLeaveDetails.StartDate
Thanks in Advance
SmileySeems like you want to convert a SQL statement from the ??? dialect to the Oracle dialect. *(It would be useful to indicate the non-ANSI standard SQL you are starting with.)
Part of the problem is that you use several date related functions. Some are unnecessary in Oracle and some need to translated into Oracle functions as found in the Functions section (chapter 5) of the SQL Reference manual at http://www.oracle.com/pls/db102/homepage
Note that columns and expressions of type 'date' in ORacle always contain all of "yyyy mm dd hh mi ss" and you need to format and trauncate as necessary.
Also note that '09-JAN-31' is NOT an Oracle date, but rather a character representation of a date which must be converted to/from a date expression. You will often need to use the to_date() and to_char() functions with a format mask as the second parameter. This is also descreibed in the first 2 chapters of the SQL Reference manual. -
Execute A select statement under Oracle connection?
Hi,
How can i execute a select statement
under an existing Oracle connecton without
defining extera JDBC connection.Be aware that you can create View Objects that are NOT based on entity objects. In this case, they are read only, but if you just want to display results, or check for a specific value, it at least reduces the overhead of an EO.
I'm not sure that answers the question here, but thought I would at least throw it out there.
In the View Object wizard, on the page that asks you to choose an EO, just click Next without selecting any EOs. This will automatically put you in expert query mode. Just type in your query and go.
You do have to be a little careful with expert mode queries, especially if you go back and edit them later. You need to make sure to keep the attribute mapping in synch on the Attribute page.
Also, I have found some limitations to this approach, which I'm not sure are fixed in 3.2. Namely, you can't use setWhereClause() to set the entire where clause string from the client. You have to use setWhereClauseParams(). This means that you have to have the basic where clause included in the query and user parameters as placeholders for the where clause values. These are JSP methods, I'm not sure what the equivalent is in DAC, but I am pretty sure the same limitation is there. -
Hi,
we are running a query with a big dunamic select statement from VB code using ADO command object. When Execute method is called system hangs and control won't return back to the application. it seems to be that there is some type limitation on Query string length. Please tell us if there is any?
we are running Oracle 8.1.7 Server on Windows 200 Server and connecting from a W2K professional, ADO 2.6 and Oracle OLEDB 8.1.7.1 OLEDB Driver.
Sample code:
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Set cmd = New Command
With cmd
.CommandText = ' some text with more than 2500 characters
.CommandType = adCmdText
Set rs = .Execute
End With
when i debug using VB6 and when .Execute line is called system hangs or return a message method <<somemethod> of <<some class name>> failed error.
Any help is appreciated.
Thanks,
AnilA stored procedure would only slow you down here if it was poorly written. I suspect you want to use the translate function. I'm cutting & pasting examples from the documentation-- a search at tahiti.oracle.com will give you all the info you'll need.
Examples
The following statement translates a license number. All letters 'ABC...Z' are translated to 'X' and all digits '012 . . . 9' are translated to '9':
SELECT TRANSLATE('2KRW229',
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'9999999999XXXXXXXXXXXXXXXXXXXXXXXXXX') "License"
FROM DUAL;
License
9XXX999
The following statement returns a license number with the characters removed and the digits remaining:
SELECT TRANSLATE('2KRW229',
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789')
"Translate example"
FROM DUAL;
Translate example
2229
Also, LIKE '%<string>%' is going to be rather expensive simply because it has to compare the entire string and because it forces full table scans, rather than using indexes. You could speed this sort of query up by using interMedia Text (Oracle Text now in 9i). If you can eliminate one of the '%' options, you could also improve things.
My guess is that your stored procedure is inefficient and that's causing the problem-- 5k rows per table should be pretty trivial.
If you post your query over on the PL/SQL forum, there are better performance tuners than I that might have more hints for you. To get really good advice, though, you'lllikely have to get at least the execution plan for this statement and may need to do some profiling to identify the problem areas.
Justin -
How to use Oracle Table Type values in Select Statement.
Hi,
I am fetching initial set of values into Oracle Table of Records Type and want to use list of values in the Select statement.
For example, try something like the following:
TYPE t_record IS RECORD (
ID TABLEA.ID%type,
NO TABLEA.NO%type,
v_record t_record;
TYPE t_table IS TABLE OF v_record%TYPE;
v_table t_table;
-- Code to populate the values in v_table here.
SELEC ID,NO, BULK COLLECT INTO <some other table variabes here> FROM TABLEA
WHERE ID IN v_table(i).ID;
I want to know how to use the values from Oracle Table Type in the Select Statement.Something like this:
create or replace type t_record as object (
id number,
no number
CREATE or replace type t_table AS TABLE OF t_record;
set serveroutput on
declare
v_table t_table := t_table();
v_t1 t_table := t_table();
begin
v_table.extend(1);
v_table(1).ID := 1;
v_table(1).No := 10;
v_table.extend(1);
v_table(2).ID := 2;
v_table(2).ID := 20;
SELEC t_record (ID,NO) BULK COLLECT INTO v_t1
from TableA
FROM TABLEA
WHERE ID IN (select t.ID from table(v_Table) t);
for i in 1..v_t1.count loop
dbms_output.put_line(v_t1(i).ID);
dbms_output.put_line(v_t1(i).No);
end loop;
end;
/Untested!
P;
Edited by: bluefrog on Mar 5, 2010 5:08 PM -
Case or decode in select statement for comparison
Hi,
How can I do a comparison
like
if sal < 50, output 1.1 * comm
if sal > 50 and < = 100 output 1.2 * comm
else output comm
in a single select statement.
I tried using case and decode but I am not sure how to use it in comparison operations.
Please helpuse the 'case' construct:
SELECT
NORMAL_FIELD
, (CASE
WHEN (SAL < 50) THEN 1.1 * COMM
WHEN (SAL > 50) AND (SAL <= 100) THEN 1.2 * COMM
ELSE COMM
END
) AS CALCULATED_COMM
FROM
TB_xxxx
WHERE xxxx
hope this helps
Maybe you are looking for
-
Can I get a refund on an itunes purchase?
I accidentally bought the wrong season when I was trying to purchase a season pass. None of the downloads have completed for the episodes. Is it possible to get a refund for this purchase?
-
How can I delete a username account that I didn't create?
Ok, so my little sister hacked in my laptop, because she doesn't have one. So she needed it for an "EMERGENCY" and I wasnt picking up my cellphone to tell her my password. So I have been trying to delete the account she made but it won't allow me too
-
External hard drive will not howon my macbook
I have a Western Digital hard drive. plug it to my comuter and its not showing up. how can i find it? or what can i do o get it to work the light does come on on the hard dive..
-
RG1 report-Ztable_entries insertion
Hi Folks, Inorder to create a RG1 report the previous development team has created a ztable of the same strcuture as J_2IRG1BAL.But I was not able to find out how they are inserting the entires into this ztable. 1.Is there any possibility that they
-
Hi, I�m having a huge problem in my JTable. I�ve got several columns in my Jtable and each cell has Double values. Some columns are editable and some aren�t. Some columns use values from anothers, i.e., they have formulas, and because of that when I