Order by clause Dynamic in Oracle function
How can i get order by Clause Dynamic in Oracle function
My function Returns sql query with SYS_REFCURSOR . and i will pass the order by column as input parameter
create or replace
FUNCTION TEST_SSK
p_srot number
RETURN SYS_REFCURSOR
AS
C_testssk SYS_REFCURSOR;
BEGIN
OPEN C_TESTSSK FOR
SELECT LOAN_CODE,LOAN_DATE,DUE_DATE,LOAN_AMT FROM LOAN_MASTER
order by P_SROT;
return C_testssk;
end;Edited by: user10736825 on Dec 22, 2010 11:34 AM
you can go for a dynamic query ;)
create or replace
FUNCTION TEST_SSK
p_srot number
RETURN SYS_REFCURSOR
AS
C_testssk SYS_REFCURSOR;
l_str VARCHAR2(4000);
l_order VARCHAR2(100);
BEGIN
l_str := 'SELECT LOAN_CODE,LOAN_DATE,DUE_DATE,LOAN_AMT FROM LOAN_MASTER ';
IF p_sort = 'LC'
THEN
l_order := ' ORDER BY LOAN_CODE ';
ELSIF p_sort = 'LD'
THEN
l_order := ' ORDER BY LOAN_DATE ';
END IF;
l_str := l_str || l_order ;
OPEN C_TESTSSK FOR l_str;
return C_testssk;
end;
Similar Messages
-
Can i assign an 'order by' clause dynamically in forms ??
I know it's possible to assign an 'order by' clause in reports with lexical parameter.
for example..
select A
from TABLE
where A is not null
&V_ORDERBY
In this, v_orderby might be 'order by name' like that,,,
can i assign an 'order by' clause dynamically IN FORMS ??
If you understan my question, please answer to me,,,ㅜㅜHave you tried this build-in function?
SET_BLOCK_PROPERTY('[BLOCK_NAME]', ORDER_BY, 'SORTCOL1, SORTCOL2...');
Where 'SORTCOL1, SORTCOL2...' are the table columns name. -
Sorting character column ( used in order by clause dynamically)
Hi,
I need help on sorting character-based numbers. Like say, I want to sort customers based on street numbers(which is a character string being used in the
order by clause) they live in.
The criteria are :
i. Numbers must take precedence.
This being a character string, 1000001 comes before 2. This shouldn't happen. And you cannot use to_number
since using it with a string having characters in it would raise an error.
ii. If only a single alphabet occurs as the last character, then treat the whole string as a number except the last character and then sort it
as if sorting a number. Something like : if you have 1000A, 200D, 200B, 1000X, the result would be 200B,200D,1000A,1000X.
iii. if a character occurs elsewhere in the string, then perform the search normally as if performing a character search.
The output of the following data :
100
A101
B100A
110C
C120B
120
100020
120C
C1100
100D
would be like :
100
100D
110C
120
120C
100020
A101
B100A
C120B
C1100
Please note that the sort is being done dynamically, so I could have access to the values of the street numbers only during run time.
Any help is really appreciated.
Thanks in advance.
Regards,
Anil.Create a function to test whether the column is numeric :
create FUNCTION is_numeric(v_number VARCHAR2)
RETURN INTEGER
IS
l_number NUMBER;
BEGIN
IF INSTR(UPPER(v_number),'E') > 0 THEN
RETURN 0;
END IF;
l_number := TO_NUMBER(v_number);
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
And try this query
Assume the table name is TEST with column STREET
select * from TEST
order by case is_numeric(STREET) when 1 then LPAD(STREET,20, ' ') else STREET end
Please make sure that 20 mentioned above is the column size for STREET.
Hope this helps.
-Nags -
How to make an ORDER BY clause dynamic
is there anyway to make the ORDER BY clause in an SQL query within a DB control
dynamic? I have tried to pass a String of the column name and place it in the
statement within {}, but it doesn't work"Mark" <[email protected]> wrote:
>
is there anyway to make the ORDER BY clause in an SQL query within a
DB control
dynamic? I have tried to pass a String of the column name and place
it in the
statement within {}, but it doesn't workDid you find how ? please let me know, I also need to have a dynamic order by
clause. -
How to use "Order by" clause dynamically on LOV values in 10g r2 forms
Hi ,
I have following requirement,please guide me.
1 Create a List Of Values with 2 fields, Code and Description
2. Do not use order by clause in record Group Query
3. Attach this LOV to a field in Form
4. When user invokes the LOV user will see two fields in LOV with header as Code and Description
5. Now when user clicks on Column Header “Code” then LOV should be sorted on Code
6. And if User clicks on Column Header “Description” then LOV should be sorted on Description
Thanks in Advance.Kindly post this problem in this forum ->
[Forms Forum|http://forums.oracle.com/forums/forum.jspa?forumID=82]
And, close this thread by marked it as answered. ;)
Regards.
Satyaki De. -
Hello,
I created a radio button to sort the data in the form.
STATIC2:Date Asc;1, Date Desc;2, Activity;3
The data is only sorted by date asc and activity asc. The sort by date desc didn't work.
ORDER BY DECODE(:P20010100_SORT,1,to_char(ENTRY_DT,'dd/mm/yyyy')|| 'Asc',2,to_char(ENTRY_DT,'dd/mm/yyyy')|| 'Desc',3,ACT_ID || 'Asc',to_char(entry_dt,'dd/mm/yyyy')|| 'Asc')
Do you have an idea how to do it ?
Thanks in advanceYou cant do order bys with ASC / DESC unless you dynamic sql or some trickery.
For example:
Make columns that reverse the values for you so that you are always sorting ASC.
order by decode(:somevar,
1,created,
2,to_date('01-jan-2999','dd-mon-yyyy')-(created)) -
How to handle Group by clause Dynamically in Oracle Form
Hi Expert,
Here i have problem :
i want display record with passing group by clause Parameter
Example :
Select zone,district,postal,count(Do_no) ,sum(Sales_Amt)
from DLV_ORD_mast
group by :zone,:district,:Postal
1-o/p like :
if user pass the :zone parameter in group by clause then record display like below o/p
zone count sls_amt
South 2 1000
central 3 5000
East 4 600
2-o/p
if use pass the :District parameter in group by clause then record display like below O/P
zone count sls_amt
South/Dist1 2 1000
central /Dist2 3 5000
central /Dist3 1 500
East /Dist4 4 600
2-o/p
if use pass the :postal parameter in group by clause then record display like below O/P
zone count sls_amt
South/Dist1/postal1 2 1000
central /Dist2/Postal2 3 5000
central /Dist3/postal3 1 500
East /Dist4/postal4 4 600
so if anybody come across same senario then Please give me the solution for this problem .
pleassssssssssssssssssssssssss
Thanks
AbhishekBuild a block one a Query FROM clause, like
SELECT GROUPCOL,
CNT,
SUMM
FROM (Select zone GROUPCOL,
count(Do_no) CNT,
sum(Sales_Amt) SUMM
from DLV_ORD_mast
group by zone
)Then at runtime, change the the block QUERY_DATASOURCE_NAME by SET_BLOCK_PROPERTY depending on the parameter, e.g. to
SELECT GROUPCOL,
CNT,
SUMM
FROM (Select zone ||', '|| DISTRICT GROUPCOL,
count(Do_no) CNT,
sum(Sales_Amt) SUMM
from DLV_ORD_mast
group by zone ||', '|| DISTRICT
) -
Hi all,
I'm creating a webpage using jsp thats accessing a mysql database. When I get a ResultSet from a query, I was wondering if anyone could give me some pointers on how I could sort the results based on a field name that someone clicks on. For example:
Column1 Column2
5 2
8 1
3 6I'd like to create hyperlinks on the field names so when a user clicks on it, it will sort the data in according to that field. Here is my code that I am trying to modify:
public String displayResultSet(ResultSet rs)
{// return a result set as an html table
String htmlTable = "";
try {
// get the number of columns
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
// create a table and display the mysql field names as table headers
htmlTable += "<TABLE>\n<TR>\n";
for(int i=1; i<=numColumns; i++)
htmlTable += "<TH>" + rsmd.getColumnName(i) + "</TH>\n";
htmlTable += "</TR>\n\n";
// create an object to temporarily hold a piece of ResultSet data
Object cellData = null;
// display the data in the ResultSet in rows of an html table
while(rs.next())
{// while the ResultSet has more rows, convert them to html
htmlTable += "<TR>";
for(int j=1; j<=numColumns; j++)
{// if the data is not null, display it, otherwise display a blank space
cellData = rs.getObject(j);
if(cellData != null)
htmlTable += "<TD>" + rs.getObject(j) + "</TD>\n";
else
htmlTable += "<TD> </TD>\n";
htmlTable += "</TR>\n\n";
htmlTable += "</TABLE>\n\n";
catch (Exception e)
{ return("Error accessing database: " + e); }
return htmlTable;
}Any help or references to where I can read up on it would be appreciated. Thanks
LeonYour display code should not be mixed in with your database code. That functionality should be seperated classes.
Generally GUIs do the ordering themselves. They do not repeatedly call the database.
But if you want you pass in a descriptor that defines the fields that will be ordered on. You optionally map that to the exact database field names. You then use StringBuilder to construct the entire SQL string and add the order by clause dynamically at the end. Then you execute it. -
ORDER BY Clause in XMLAGG is throwing errors.
Hi,
I'm getting errors when generating the XML using the ORDER BY clause in the XMLAgg function. Although, running the SQL directly in SQL Plus doesn't have any problem.
Here is the PL/SQL sample.
DECLARE
vX_XML SYS.XMLTYPE;
vCL_XML CLOB;
BEGIN
SELECT XMLElement("GROUP",
XMLAttributes(Group_Id AS "ID", Group_Name AS "NAME", Group_Description AS "DESC"),
XMLAgg(XMLElement("FIELD",
XMLAttributes(Field_Id AS "ID", Field_Description AS "DESC",
Table_Name AS "TAB_NM", Rule_Name AS "RULE_NM",
Field_Hierarchy_Depth AS "DOL_VAR_CALC")) ORDER BY Field_Description))
INTO vX_XML
FROM (SELECT g.Group_Id, g.Group_Name, g.Group_Description, f.Field_Id, f.Field_Description,
DECODE(f.Table_Name, 'ESTIMATES', 'E', 'LINE_ITEMS', 'L', NULL) Table_Name,
rt.Rule_Name,
CASE NVL(f.Field_Hierarchy_Depth, 0) WHEN 0 THEN 'N' ELSE 'Y' END Field_Hierarchy_Depth
FROM GROUPS g,
Rules r,
Rule_Types rt,
Fields f
WHERE g.Group_Id = 3087
AND r.Group_Id_Fk = g.Group_Id
AND rt.Rule_Type_Id = r.Rule_Type_Id_Fk
AND f.Field_Id = r.Field_Id_Fk) tab
GROUP BY Group_Id, Group_Name, Group_Description;
vCL_XML := vX_XML.GetCLOBVal();
END;
And, here are the errors.
ERROR at line 8:
ORA-06550: line 8, column 23:
PLS-00306: wrong number or types of arguments in call to 'XMLAGG'
ORA-06550: line 8, column 23:
PL/SQL: ORA-00904: "XMLAGG": invalid identifier
ORA-06550: line 6, column 5:
PL/SQL: SQL Statement ignored
Thanks in Advance.
BTW, we are using Oracle 9.2.0.4.This is bug 2785463 with no ETA for a fix
regards
Coby D. Adams Jr. -
HAVING clause, or ORDER BY clause ....ERROR
hi i have following query which throws error plz find the solution for the query to go safe..
Select C.src_cd,
D.src_nm,
count(*) supp_clm_count,
(CASE WHEN A.clm_ttladjamt > 0 then A.clm_ttladjamt else A.clm_ttlreqamt END) as amount
From IWOWNER.WC_clm A,
IWOWNER.WC_clm_srvc B,
SHOWNER.WC_SRC C,
SHOWNER.WC_SRC_lang D
where A.clm_id = B.clm_id
and A.rcv_loc_id = C.src_id
and C.src_id = D.src_id
and TRANSLATE(A.clm_rqst_type_cd) = 'SUPPLIERCLAIM'
and TRANSLATE(A.clm_typ_cd) in ('WARRANTY','PRE-DELIVERY')
and DATE(A.clm_create_dt) between '01/01/2000' and '01/01/2010'
Group by C.src_cd, D.src_nm
ERROR:
SQLSTATE: 42803, SQLERRMC: CLM_TTLADJAMT
Message: An expression starting with "CLM_TTLADJAMT" specified in a SELECT clause, HAVING clause, or ORDER BY clause is not specified in the GROUP BY clause or it is in a SELECT clause, HAVING clause, or ORDER BY clause with a column function and no GROUP BY clause is specifiedHi,
With analytic function
/* Formatted on 2009/07/22 10:47 (Formatter Plus v4.8.8) */
SELECT DISTINCT c.src_cd, d.src_nm,
COUNT (1) OVER (PARTITION BY c.src_cd, d.src_nm)
supp_clm_count,
SUM (CASE
WHEN a.clm_ttladjamt > 0
THEN a.clm_ttladjamt
ELSE a.clm_ttlreqamt
END
) OVER (PARTITION BY c.src_cd, d.src_nm) AS amount
FROM iwowner.wc_clm a,
iwowner.wc_clm_srvc b,
showner.wc_src c,
showner.wc_src_lang d
WHERE a.clm_id = b.clm_id
AND a.rcv_loc_id = c.src_id
AND c.src_id = d.src_id
AND a.clm_rqst_type_cd = 'SUPPLIERCLAIM'
AND a.clm_typ_cd IN ('WARRANTY', 'PRE-DELIVERY')
AND a.clm_create_dt BETWEEN TO_DATE ('01/01/2000', 'dd/mm/yyyy')
AND TO_DATE ('01/01/2010', 'dd/mm/yyyy') -
Using oracle function in order by clause
Hello,
can i use report query or report that generate query like this :
select fname, lname from peoples order by dbms_random.value;
dbms_random is an oracle function to generate random value.
Thnaksadd the following call to your query:
query.addOrdering(query.getExpressionBuilder().getFunction("dbms_random.value"));
--Gordon -
[JPA/TOPLINK] is the function "lower" supported in "order by" clause?
In EJB-QL
I can use lower() or upper() in where clause.
But there is always a parse exception thrown when i tried to use it in main clause or order by clause.
works:
select s from Student s where lower(s.name) like 'm%'
exception thrown:
select s from Student s where s.name like 'm%' order by lower(s.name)
OR --------------
Why i am asking this is that the resultset returned from database is not alphabetical sorted but ascii sorted, which means any characters with upper case is always prior to the ones with lower case.
If EJB-QL doesn't support using lower() in order by clause, do I have any other options to avoid this problem?
BTW, it is the Oracle 10g we are using as DB
many thanks,
Xuphey
Edited by: Xuphey on Nov 29, 2007 1:33 AMIf you want to do this, you'd have to use dynamic SQL (execute immediate or DBMS_SQL). For the easier 'execute immediate' approach, you'd do something like
create or replace someProc( someArg varchar2 )
as
strSQL varchar2(4000)
begin
strSQL := <<string containing your SQL statement up to the order by clause>>
strSQL := strSQL || 'ORDER BY ' || someArg
execute immediate strSQL;
endJustin -
I need to dynamically build the order by clause of my query.
I tried this:
<named-query name="list">
<query>
<![CDATA[
SELECT p FROM Person p
ORDER BY :orderby
]]>
</query>
</named-query>
@SuppressWarnings("unchecked")
public List<Person> list(String sort) {
Query query = getEntityManager().createNamedQuery("list");
query.setParameter("orderby", sort);
return query.getResultList();
}But at runtime it throws an exception:
com.microsoft.sqlserver.jdbc.SQLServerException:
L'elemento SELECT identificato da ORDER BY 1 include una variabile nell'espressione che identifica la posizione di una colonna.
Le variabili sono consentite solo nell'ordinamento in base a un'espressione che fa riferimento a un nome di colonna.The translation of the italian message is something like:
The SELECT element identified by ORDER BY 1 includes a variable that identifies the position of a column.
The valid variables in the order by clause must refer to the name of a columnThe value of the parameter sort is_ the name of a column!
Any hint?My solution was to append the order clause to an "namedQuery" like this:
- declare the named query as usual, with annotation
- create a simple helper function like findNamedQuery to find the query string for a given class and queryName (using reflection)
- if you need to execute the query without sort order - use EntityManager.createNamedQuery (as usual)
- BUT: if you want to sort data: use EntityManager.createQuery with the string obtained from findNamedQuery and the sort clause
I guess the is a performance penalty, but.. .it works. -
Sorting technique used by oracle for "order by" clause.
Hi All,
it could be very help to me if you provide some information about sorting technique used by oracle engine for order by clause.
Issue i am facing :
Table : xx
Line Date
1 05-06-2013 00:00:00
2 05-06-2013 00:00:00
when we query above table using order by date, it is returning line 2 prior to line 1. we would like to know why it is returning line 2 first?
Regards,
Ram>
it could be very help to me if you provide some information about sorting technique used by oracle engine for order by clause.
>
Well ok - but be warned that many people wind up being sorry they ask that question. Hopefully Hemant's answer is what you really wanted.
See 'Linguistic Sorting and String Searching' in the Oracle® Database Globalization Support Guide
http://docs.oracle.com/cd/B28359_01/server.111/b28298/ch5lingsort.htm
Sorting will be controlled by the settings of NLS_LANGUAGE, NLS_SORT and NLS_COMP.
Here is the doc page for NLS_SORT
http://docs.oracle.com/cd/B28359_01/server.111/b28298/ch3globenv.htm#i1008393
>
NLS_SORT specifies the type of sort for character data. It overrides the default value that is derived from NLS_LANGUAGE.
NLS_SORT contains either of the following values:
NLS_SORT = BINARY | sort_name
BINARY specifies a binary sort. sort_name specifies a linguistic sort sequence.
>
And the one for NLS_COMP
http://docs.oracle.com/cd/B28359_01/server.111/b28298/ch3globenv.htm#i1008458
>
The value of NLS_COMP affects the comparison behavior of SQL operations.
You can use NLS_COMP to avoid the cumbersome process of using the NLSSORT function in SQL statements when you want to perform a linguistic comparison instead of a binary comparison. When NLS_COMP is set to LINGUISTIC, SQL operations perform a linguistic comparison based on the value of NLS_SORT. A setting of ANSI is for backward compatibility; in general, you should set NLS_COMP to LINGUISTIC when you want to perform a linguistic comparison. -
Error : The ORDER BY clause is invalid in views, inline functions, derived
Hi All,
I am on 11g 6.2, Windows Server 2008, my db SQL server 2008, I am facing the error for the reports in which I am trying to edit one the column formula and do something like 'abc/sum(abc)*100'.
10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 43113] Message returned from OBIS. [nQSError: 43119] Query Failed: [nQSError: 16001] ODBC error state: 37000 code: 8180 message: [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared.. [nQSError: 16001] ODBC error state: 37000 code: 1033 message: [Microsoft][ODBC SQL Server Driver][SQL Server]The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.. [nQSError: 16002] Cannot obtain number of columns for the query result. (HY000)
One of the solutions to this which I have found is to edit the EXPRESSION_IN_ORDERBY_SUPPORTED feature in the db properties.
I want to know what does EXPRESSION_IN_ORDERBY_SUPPORTED means?
When I create a calculations in 11g like abc/sum(abc) in the column formula for a column then i get this error.
What does this error mean? Does OBIEE 11g doesn't support using these expressions in the report and the fact that it applies the order by clause to the reports, the report fail?
Could anybody please explain the issue. There is very limited information on this over the web.
Thanks in advance.
RonnyThanks svee for the quick response, actually i had resolved the issue by unchecking the EXPRESSION_IN_ORDERBY_SUPPORTED option in the database. I want to understand how does that makes the difference?
What does EXPRESSION_IN_ORDERBY_SUPPORTED mean? Does it mean that if I give any expression in my answers report and since obiee uses a order by for all the queries, the expression won't be supported?
Please explain.
Maybe you are looking for
-
Selecting fields those which contains values from a table of one record
hello Is it possible to select the fields of a table having not null values for a single record. The record contains 25 fields like FieldNames are Field1, Field2......Field25 if Field1 and Field12 has some not null values and other fields contain nul
-
My computer crashes when I try to print.My
My computer crashes when I try to print to my Epson Photo R1800 printer from either light room 5 or photoshop CS5. I'm using a mac with X.8.4. Has anyone had similar problems. Thanks
-
HT201441 what if the previous owner is not available how am i going to use the phone?
i have iphone4 which i bought from a friend but there is no way i can contact him i have reset the phone but its asking his icloud account to do the reset how can i remove his account
-
Adobe Reader 10 won't start sometimes
I rely on Adobe Reader 10 for my little home based business. I'm using Windows 7 and lately, at times, I cant get the reader to open when I click on a file. It MAY have something to do with after I wake the computer up when it went to sleep, but I'm
-
COPA - Planned Material Cost not appearing in KE30 report
Hi all In COPA planning, I manually planned the Material cost (Material External Price) along with the Sales Quantity and Revenue for two company codes (one plant in each co code). But in KE30 report, I could see the material cost (MEP) values only