Use of ROW_NUMBER() function in PL/SQL
I have a Table Emp with the following Structure
SQL> desc emp
Name Null? Type
EMPNO NUMBER(2)
ENAME VARCHAR2(50)
HIREDATE DATE
DEPTNO NUMBER(2)
If I write a following query on this table
SQL> SELECT deptno, hiredate, record_id
2 FROM (SELECT deptno, ename, hiredate, ROW_NUMBER()
3 OVER (ORDER BY hiredate) AS record_id
4 FROM emp)
5 WHERE record_id >= 2
6 AND record_id <=5;
The Result I get is
DEPTNO HIREDATE RECORD_ID
10 22-NOV-01 2
10 22-NOV-01 3
10 22-NOV-01 4
10 22-NOV-01 5
But if I put this query in a cursor in a PL/SQL block. The
pl/sql does not compiles and gives me the following address
SQL> DECLARE
2 CURSOR c_my IS
3 SELECT deptno, hiredate, record_id
4 FROM (SELECT deptno, ename, hiredate, ROW_NUMBER()
5 OVER (ORDER BY hiredate) AS record_id
6 FROM emp)
7 WHERE record_id >= 2
8 AND record_id <=5;
9 BEGIN
10 FOR c_rec IN c_my LOOP
11 dbms_output.put_line(c_rec.ename);
12 END LOOP;
13 END;
14 /
OVER (ORDER BY hiredate) AS record_id
ERROR at line 5:
ORA-06550: line 5, column 13:
PLS-00103: Encountered the symbol "(" when expecting one of the
following:
, from
Question: Can you please tell me how I can use the ROW_NUMBER()
function in PL/SQL. I need to use this for selecting the correct
range of records for Pagination on a website.
Thanks in advance
Prashant
As Andrew said, PL/SQL hasn't caught up with the newer bits of
SQL. I have heard that in 9i, they will be the same, but in 8i
there are still things that you can do in SQL that you cannot do
directly in PL/SQL, such as the new functions like ROW_NUMBER.
However, you can use NDS as a work around. The following does
the same as what you posted:
SET SERVEROUTPUT ON
DECLARE
TYPE c_my_type IS REF CURSOR;
c_my c_my_type;
TYPE c_rec_type IS RECORD
(deptno emp.deptno%TYPE,
ename emp.ename%TYPE,
hiredate emp.hiredate%TYPE,
record_id INTEGER);
c_rec c_rec_type;
v_sql VARCHAR2 (4000);
BEGIN
v_sql :=
'SELECT deptno, ename, hiredate, record_id
FROM (SELECT deptno, ename, hiredate,
ROW_NUMBER() OVER
(ORDER BY hiredate)
AS record_id
FROM emp)
WHERE record_id >= 2
AND record_id <= 5';
OPEN c_my FOR v_sql;
LOOP
FETCH c_my INTO c_rec;
EXIT WHEN c_my%NOTFOUND;
DBMS_OUTPUT.PUT_LINE (c_rec.ename);
END LOOP;
END;
However, you stated that you need it for selecting the correct
range of records for pagination on a website. For that, you
will want something more like this:
CREATE OR REPLACE PACKAGE package_name
AS
TYPE c_my_type IS REF cursor;
PROCEDURE procedure_name
(c_my IN OUT c_my_type,
p_record_id1 IN NUMBER DEFAULT 1,
p_record_id2 IN NUMBER DEFAULT 4);
END package_name;
CREATE OR REPLACE PACKAGE BODY package_name
AS
PROCEDURE procedure_name
(c_my IN OUT c_my_type,
p_record_id1 IN NUMBER DEFAULT 1,
p_record_id2 IN NUMBER DEFAULT 4)
IS
v_sql VARCHAR2 (4000);
BEGIN
v_sql :=
'SELECT deptno, ename, hiredate, record_id'
|| ' FROM (SELECT deptno, ename, hiredate,'
|| ' ROW_NUMBER() OVER'
|| ' (ORDER BY hiredate)'
|| ' AS record_id'
|| ' FROM emp)'
|| ' WHERE record_id >= :a'
|| ' AND record_id <= :b';
OPEN c_my FOR v_sql
USING p_record_id1, p_record_id2;
END procedure_name;
END package_name;
Similar Messages
-
WITHOUT USING ROW_NUMBER FUNCTIONS IN T-SQL
INPUT:-
CUST_ID
GIFT_ID
100
10
100
20
100
30
200
10
200
20
200
30
300
20
OUTPUT:-
CUST_ID
GIFT_ID
SEQ
100
10
1
100
20
2
100
30
3
200
10
1
200
20
2
200
30
3
300
20
1
santoshbangaloreTHANK YOU SO MUCH FOR YOUR ANS? BUT MY INPUT TABLE A CONTAIN ONLY TWO COLUMN'S
CUST_ID,GIFT_ID
AND IN OUT PUT I NEED THE ABOVE OUTPUT WITH
CUST_ID,GIFT_ID,ROW_NUMBER AS SHOWN ABOVE?
santoshbangalore -
Yielding the desired number of decimal places using the AVG function in t-sql
Hello again. Confused retired hobby coder having trouble setting up a scalar-valued function to return the desired number of decimal places from a AVG query.
Whenever I run the following script I get the number of decimals I desire:
Using the above I created a scalar-valued function as follows:
Running this function as: SELECT [dbo].[TestHCIPartial] (1,3) my return is -7.
Can you help me with the function causing it to yield the answer to 6 decimal places?
Thanks and regards, Minuend.You've not specified precision and scale in UDF return type. So you're leaving it to server to interpret it based on default settings
If you want exactly up to four decimal places tweak udf as below
ALTER FUNCTION..
RETURNS decimal(20,4)
AS
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
Need help in using sleep function in pl/sql
Hi,
need help:
I have a condition where i want to validate total_pass=total_fail and
I want to use the sleep function in a pl/sql where i want to wait for 2 minutes ie.checking
whether total_pass=total_fail based upon class_id .
I have the data in the table as:
CLASS_ID TOT_PASS TOT_FAIL
1 10 10
2 5 4
3 6 6
4 7 5
Any help will be needful for meI'm not quite sure what you are lookg for here, but whatever it is, your code as posted won't do it. You will never break out of the WHILE r_Class.Tot_Pass = r_Class.Tot_Fail loop, since these values will never change because you never get the next record form the cursor.
From your original data, it looks like your cursor will return multiple rows which implies to me that you want to fetch the first row from the cursor, check if tot_pass = tot_fail, if they are equal, sleep for two minutes then get the next row. This does not make sense to me. Once the select in the cursor is executed, the data it returns will not change due to Oracle's read consistency model, so there seems to me no point in the sleep.
The other alternative I can see is that you want to check all the returned rows, and if tot_pass = tot_fail for one of the rows (or possibly for all of the rows), then you want to sleep and try again.
If you can explain in words what it is you are trying to accomplish, someone will be able to point you to a solution.
John -
Using User Defined Function is SQL
Hi
I did the following test to see how expensive it is to use user defined functions in SQL queries, and found that it is really expensive.
Calling SQRT in SQL costs less than calling a dummy function that just returns
the parameter value; this has to do with context switchings, but how can we have
a decent performance compared to Oracle provided functions?
Any comments are welcome, specially regarding the performance of UDF in sql
and for solutions.
create or replace function f(i in number) return number is
begin
return i;
end;
declare
l_start number;
l_elapsed number;
n number;
begin
select to_char(sysdate, 'sssssss')
into l_start
from dual;
for i in 1 .. 20 loop
select max(rownum)
into n
from t_tdz12_a0090;
end loop;
select to_char(sysdate, 'sssssss') - l_start
into l_elapsed
from dual;
dbms_output.put_line('first: '||l_elapsed);
select to_char(sysdate, 'sssssss')
into l_start
from dual;
for i in 1 .. 20 loop
select max(sqrt(rownum))
into n
from t_tdz12_a0090;
end loop;
select to_char(sysdate, 'sssssss') - l_start
into l_elapsed
from dual;
dbms_output.put_line('second: '||l_elapsed);
select to_char(sysdate, 'sssssss')
into l_start
from dual;
for i in 1 .. 20 loop
select max(f(rownum))
into n
from t_tdz12_a0090;
end loop;
select to_char(sysdate, 'sssssss') - l_start
into l_elapsed
from dual;
dbms_output.put_line('third: '||l_elapsed);
end;
Results:
first: 303
second: 1051
third: 1515
Kind regards
TaoufikI find that inline SQL is bad for performance but
good to simplify SQL. I keep thinking that it should
be possible somehow to use a function to improve
performance but have never seen that happen.inline SQL is only bad for performance if the database design (table structure, indexes etc.) is poor or the way the SQL is written is poor.
Context switching between SQL and PL/SQL for a User defined function is definitely a way to slow down performance.
Obviously built-in Oracle functions are going to be quicker than User-defined functions because they are written into the SQL and PL/SQL engines and are optimized for the internals of those engines.
There are a few things you can do to improve function
performance, shaving microseconds off execution time.
Consider using the NOCOPY hints for your parameters
to use pointers instead of copying values. NOCOPY
is a hint rather than a directive so it may or may
not work. Optimize any SQL in the called function.
Don't do anything in loops that does not have to be
done inside a loop.Well, yes, but it's even better to keep all processing in SQL where possible and only resort to PL/SQL when absolutely necessary.
The on-line documentation has suggested that using a
DETERMINISTIC function can improve performance but I
have not been able to demonstrate this and there are
notes in Metalink suggesting that this does not
happen. My experience is that DETERMINISTIC
functions always get executed. There's supposed to
be a feature in 11g that acually caches function
return values.Deterministic functions will work well if used in conjunction with a function based index. That can improve access times when querying data on the function results.
You can use DBMS_PROFILER to get run-time statistics
for each line of your function as it is executed to
help tune it.Or code it as SQL. ;) -
SQL Query (PL/SQL function body returning SQL query) when using to_char
we are trying to build a report page of Type SQL Query (PL/SQL function body returning SQL query).
our query is so simple, we need to extract the month from the recording_date column.
declare
l_query varchar2(1000);
begin
l_query:='select to_char(recording_date,'MM')from re_productive';
return l_query;
end;
but we are having the following problem for this query
Function returning SQL query: Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the generic columns checkbox below the region source to proceed without parsing.
(ORA-06550: line 4, column 42: PLS-00103: Encountered the symbol "MON" when expecting one of the following: . ( * @ % & = - + ; < / > at in is mod remainder not rem <> or != or ~= >= <= <> and or like between || multiset member SUBMULTISET_ The symbol ". was inserted before "MON" to continue.)
Notes:
1-the query is correct and it was tested under Toad and SQL Plus.
2- we tried Use Generic Column Names (parse query at runtime only) option but we get the same problem.
any quick help please.Hi
You haven't escaped your quotes in the string. Try this...
DECLARE
l_query VARCHAR2(32767);
BEGIN
l_query:= 'select to_char(recording_date,''MM'') from re_productive';
RETURN l_query;
END;Cheers
Ben -
Hello guys,
I'm writing a stored procedure which tries to convert a string representing a number to a fixed size number(with 2 positions fraction). For example, if the input was "15,456" the result would become 15.45.
I was able to aschieve this ussing the CAST function within a query as follows:
select cast ('15,456' as number(15,2)) from dual; -- (the comma in my case is configured as fraction separator). The previous query executes OK using a query analyzer like SQL Plus.
However, when I try to use the same function within a stored procedure, it will complain about the number's size (15,2) and wont compile.
v_importe_ingresado := CAST('15,456' AS NUMBER(15,2));
Error output: PLS-00103 found '(' but expected one of the following: .)@%
When removing the (15,2) it compiles ok
¿Any clue?
I will appreciate any help.
Thanks in advance,
Bernabé¿Any clue?¿¿¿Over complication???
SQL> select round(15.456, 2), trunc(15.456, 2) from dual
2 /
ROUND(15.456,2) TRUNC(15.456,2)
15.46 15.45
SQL> Cheers, APC
Blog : http://radiofreetooting.blogspot.com/ -
Equivalent of to_date function in Ms SQL and using it in Evaluate function
Hi,
I am trying to find out a function in MS SQL which is equivalent to to_date function in oracle. Please find below the advanced filter i am trying to use in OBIEE.
Evaluate('to_date(%1,%2)' as date ,SUBSTRING(TIMES.CALENDAR_MONTH_NAME FROM 1 FOR 3)||'-'||cast(TIMES.CALENDAR_YEAR as char(4)),'MON-YYYY')>=Evaluate('to_date(%1,%2)' as date,'@{pv_mth}'||'@{pv_yr}','MON-YYYY') and Evaluate('to_date(%1,%2)' as date ,SUBSTRING(TIMES.CALENDAR_MONTH_NAME FROM 1 FOR 3)||'-'||cast(TIMES.CALENDAR_YEAR as char(4)),'MON-YYYY') <=timestampadd(sql_tsi_month,4,Evaluate('to_date(%1,%2)' as date,'@{pv_mth}'||'@{pv_yr}','MON-YYYY'))
The statement above works fines with oracle DB with to_date function. The same statement throws an error with MS SQL since to_date is not a built in function.
With MS SQL I tried with CAST, not sure how to pass parameters %1 and %2.
Please help me how to use Evaluate function and passing parameters along with to_date funtion in MS SQL.
Regards!
RRHi,
please refer to this thread for useful information on using to_char and to_date functions of oracle in MS SQL server:
http://database.ittoolbox.com/groups/technical-functional/sql-server-l/how-to-write-to-to_char-and-to_date-sql-server-351831
Hope this helps.
Thanks,
-Amith. -
Using UTL_HTTP.GET_RESPONSE function (PL/SQL)
Hello,
I have a problem using the UTL_HTTP.GET_RESPONSE (URL, 'POST') function while I try to call a function that returns an XML;
The function returning my XML is:
FUNCTION MyFunction return XMLTYPE is
begin
return XMLTYPE('<PROVA>test</PROVA>');
end MyFunction;
To perform the http call I use this function:
FUNCTION POST(URL VARCHAR2, DATA_IN CLOB) RETURN CLOB IS
BEGIN
DECLARE
DATA_OUT CLOB;
PIECE VARCHAR2(4000);
AMT PLS_INTEGER := 4000;
POS PLS_INTEGER := 1;
HTTP_REQ UTL_HTTP.REQ;
HTTP_RESP UTL_HTTP.RESP;
BEGIN
HTTP_REQ := UTL_HTTP.BEGIN_REQUEST (URL, 'POST');
UTL_HTTP.SET_HEADER(HTTP_REQ, 'content-length', LENGTH(DATA_IN));
LOOP
DBMS_LOB.READ(DATA_IN,AMT,POS,PIECE);
UTL_HTTP.WRITE_TEXT(HTTP_REQ, PIECE);
EXIT WHEN AMT < 4000;
POS := POS + AMT;
AMT := 4000;
END LOOP;
HTTP_RESP := UTL_HTTP.GET_RESPONSE (HTTP_REQ);
BEGIN
LOOP
UTL_HTTP.READ_TEXT(HTTP_RESP, PIECE);
DATA_OUT := DATA_OUT || PIECE;
END LOOP;
EXCEPTION WHEN UTL_HTTP.END_OF_BODY THEN NULL;
END;
UTL_HTTP.END_RESPONSE (HTTP_RESP);
RETURN DATA_OUT;
END;
END;
The script pl/sql that calls the preceding function is:
declare
v_resp CLOB;
v_url VARCHAR2(4000);
begin
v_url := 'http:// ... /meters.export_table.MyFunction'
v_resp := POST(v_url, '-');
end;
After this call to my url, the variabile v_resp contains the following error message:
"<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>400 Bad Request</TITLE>
</HEAD><BODY>
<H1>Bad Request</H1>
Your browser sent a request that this server could not understand.<P>
mod_plsql: /pls/prjsi/meters.export_table.MyFunction HTTP-400 Missing '=' in query string or post form<P>
<HR>
<ADDRESS>Oracle-Application-Server-10g/10.1.2.0.2 Oracle-HTTP-Server Server at websvil.aem.torino.it Port 80</ADDRESS>
</BODY></HTML>"
Do you know how I can get my XML? What is the problem in that call http for my function?
ThanksHello !
I have not understand exactly what have you try to achieve with your code , but i thing there are few things misunderstood in your code ,
so i'm posting this very basic but working example in hope that it will help you
SQL>
SQL>
SQL> conn scott/tiger
Connected.
SQL>
SQL>
SQL> create or replace procedure http_test is
2 begin
3 htp.p('<PROVA>test</PROVA>');
4 end http_test;
5 /
Procedure created.
SQL> CREATE OR REPLACE function HTTP_POST return varchar2 is
2
3 req utl_http.req;
4 resp utl_http.resp;
5
6 v_txt varchar2(1024);
7
8 BEGIN
9
10 req := UTL_HTTP.begin_request ('http://localhost:7777/pls/my_utf8/http_test'
11 ,'POST','HTTP/1.1');
12 Utl_Http.Set_Authentication ( r => req, username => 'scott', password => 'tiger'
13 , scheme => 'Basic', for_proxy => false );
14 resp := UTL_HTTP.get_response (req);
15 utl_http.read_text(resp,v_txt);
16 utl_http.end_response(resp);
17 return v_txt;
18 END;
19 /
Function created.
SQL> select http_post from dual;
HTTP_POST
<PROVA>test</PROVA>
SQL> T -
Hello every one, can I rewrite the following query without using the 'ROW_NUMBER() OVER ' part.
The query is supposed to pull out the records whose CODE is not NULL and has most
recent date for UPDATE_DATE . The reason I wanted to do this is, When I embed this query
in between many other queries along with JOINs, My oracle server is unable to execute. So, I thought
its better to supplant 'ROW_NUMBER() OVER ' logic with something else and try it. .
SELECT a.* FROM
(SELECT b.*, ROW_NUMBER() OVER (PARTITION BY b.PIDM
ORDER BY b.UPDATE_DATE DESC) AS Rno
FROM
SELECT *
FROM SHYNCRO WHERE CODE IS NOT NULL
)b
)a
WHERE a.Rno = 1Hi,
You didn't write over 150 lines of code and then start testing it, did you?
Don't.
Take baby steps. Write as little as pssiblem test that. Debug and test again until you have something that does exactly what you want it to do.
When you have somehting that works perfectly, take one baby step. Add a tiny amount of code, maybe 1 or 2 lines more, and test again.
When you do get an error, or wrong results, you'll have a much better idea of where the problem is. also, you won't be building code on a flimsy foundation.
If you need help, post the last working version and the new version with the error. Explain what you're trying to do in the new version.
The error message indicates line 133. It looks like line 133 of your code is blank. Does your front end allow completely blank lines in the middle of a query? SQL*Plus doesn't by default; you have to say
SET SQLBLANKLINES ONto have a completely blank line in SQL*Plus. (However, lines containing nothing but at commnet are always allowed.)
You may have noticed that this site normally doesn't display multiple spaces in a row.
Whenever you post formatted text (such as indented code) on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
The 4 people who posted small code fragments for you to read all did this. It would be so much easier for people to read your humongeous query if it were formatted. -
Using Package to produce pl/sql function body returning sql query Report
I have existing code that we want to use in building reports in APEX. We are needing to modify it slightly to handle some new requirements, but would like to use them in reports based upon SQL query (pl/sql function body returning sql query) functionality.
Any suggestions as how to call these in an APEX report region?
Thank you,
Tony Miller
UTMB/EHNHi Tony-
I am also v new to Apex and you may have answered a question I was in search of. I, however, now have a couple more. First a bit of background-- Like in your situation, my college has a lot of existing code (400 +) that we need to get into Apex. The majority of this canned code contains one/both: 1) many lines, sometimes containing multiple select statements 2) imbedded create table & view statements (temp user owned). Up until reading your post, I was unable to figure out an easy way of getting this existing code into the product. Thanks. Now the questions, do you know how I would go about dealing with the create tables/views. I've read some posts on this forum which suggest temporary tables being unstable in this environment. Also, do you know if there's a size limitation when passing sql code via a function?
As you may/may not be able to tell, I'm a bit lost right now... so any info you can provide would be appreciated. Thanks.
Don -
Derive found flag in SQL with where clause using TABLE(CAST function
Dear All,
Stored procedure listEmployees
==========================
CREATE OR REPLACE TYPE STRING_ARRAY AS VARRAY(8000) OF VARCHAR2(15);
empIdList STRING_ARRAY
countriesList STRING_ARRAY
SELECT EMP_ID, EMP_COUNTRY, EMP_NAME, FOUND_FLAG_
FROM EMPLOYEE WHERE
EMP_ID IN
(SELECT * FROM TABLE(CAST(empIdList AS STRING_ARRAY))
AND EMP_COUNTRY IN
(SELECT * FROM TABLE(CAST(countriesList AS STRING_ARRAY))
=================
I have a stored procedure which lists the employees using above simple query.
Here I am using table CAST function to find the list of employees in one go
instead of looping through each and every employee
Everything fine until requirements forced me to get the FOUND_FLAG as well.
Now I wanted derive the FOUND_FLAG by using rownum, rowid, decode functions
but I was not successful
Can you please suggest if there is any intelligent way to say weather the
row is found for given parameters in the where clause?
If not I may have to loop through each set of empIdList, countriesList
and find the values individually just to set a flag. In this approach I can’t use
the TABLE CAST function which is efficient I suppose.
Note that query STRING_ARRAY is an VARRAY. It is very big in size and this procedure
suppose to handle large sets of data.
Thanks In advance
Regards
Charan
Edited by: kmcharan on 03-Dec-2009 09:55
Edited by: kmcharan on 03-Dec-2009 09:55If your query returns results, you have found them... so your "FOUND" flag might be a constant,...
-
Ms Access Last function equivalent function in T-SQL
Hi,
I am new to SQL Server. I have table with information below. Some provider is listed twice in the table
Provider Code
Outlet Code
Provider
Province
Phone
First Visit Date
Last Visit Date
Supervision Score (%)
Score of Critical Steps
IUD Percentage of Critical Steps
80% Country Quality Service
Critical Step
Meet Quality Guideline
5188
01-00-0068
HENG Vuoch Eng
Banteay Meanchey
(012) 958-919
4/2/2014
4/2/2014
91.66
2.43
81.37
No
No
No
5188
01-00-0068
HENG Vuoch Eng
Banteay Meanchey
(012) 958-919
28-05-2014
28-05-2014
87.96
2.43
81.37
Yes
Yes
Yes
5410
01-00-0110
Chhuoy Pannada
Banteay Meanchey
(016) 865-985
18-03-2014
18-03-2014
85.18
2.52
84.31
Yes
Yes
Yes
5190
01-00-0123
Nhek Puthary
Banteay Meanchey
(012) 217-175
8/1/2014
8/1/2014
84.25
2.29
76.47
No
Yes
No
5190
01-00-0123
Nhek Puthary
Banteay Meanchey
(012) 217-175
22-05-2014
22-05-2014
83.33
2.29
76.47
No
Yes
No
5413
01-00-0184
Kou Mom
Banteay Meanchey
(097) 787-8280
11/2/2014
11/2/2014
89.81
2.64
90.19
n/a
Yes
n/a
5413
01-00-0184
Kou Mom
Banteay Meanchey
(097) 787-8280
27-02-2014
27-02-2014
98
2.64
90.19
Yes
Yes
Yes
5634
01-00-0264
Yoeub Chakriya
Banteay Meanchey
(012) 938-538
22-05-2014
22-05-2014
88.88
2.64
88
Yes
No
No
5542
01-00-0601
Ngann Ratha
Banteay Meanchey
(012) 201-406
20-05-2014
20-05-2014
87.81
2.23
74.33
No
Yes
No
5532
01-00-0913
Em Mouth
Banteay Meanchey
(012) 447-674
6/3/2014
6/3/2014
92.59
2.79
93.13
Yes
Yes
Yes
5532
01-00-0913
Em Mouth
Banteay Meanchey
(012) 447-674
6/6/2014
6/6/2014
92.59
2.79
93.13
Yes
Yes
Yes
5554
01-00-0920
Boa Tay
Banteay Meanchey
(012) 985-539
18-03-2014
18-03-2014
84.4
2.26
75.49
No
Yes
No
5554
01-00-0920
Boa Tay
Banteay Meanchey
(012) 985-539
17-06-2014
17-06-2014
85.18
2.26
75.49
No
Yes
No
5535
01-00-0922
Say Sav Dy
Banteay Meanchey
(012) 764-632
4/3/2014
4/3/2014
79.62
2.47
86.28
No
Yes
No
5535
01-00-0922
Say Sav Dy
Banteay Meanchey
(012) 764-632
19-06-2014
19-06-2014
79.62
2.47
86.28
Yes
No
No
5414
01-00-0963
Thorn Sao Rouey
Banteay Meanchey
(012) 673-017
9/4/2014
9/4/2014
82.4
2.58
86
Yes
Yes
Yes
In Ms Access, I can reproduce list of unique provider using the last function (see table below)
How can I do it in SQL Server?
Provider Code
Outlet Code
Provider
Province
Phone
FirstOfFirst Visit Date
LastOfLast Visit Date
LastOfSupervision Score (%)
LastOfScore of Critical Steps
LastOfIUD Percentage of Critical Steps
LastOf80% Country Quality Service
LastOfCritical Step
LastOfMeet Quality Guideline
5137
06-00-0417
Kang Sophalna
Kampong Thom
(092) 954-367
22-04-2014
22-04-2014
87.03
3
100
Yes
Yes
Yes
5138
06-00-0415
Nou Vichetra
Kampong Thom
(012) 773-102
20-03-2014
12/6/2014
96.29
3
100
Yes
Yes
Yes
5140
06-00-0254
Yim Cheng Sim
Kampong Thom
(012) 725-597
4/3/2014
6/6/2014
96.29
3
100
Yes
Yes
Yes
5143
06-00-0868
Long Chanthida
Kampong Thom
(012) 682-009
20-05-2014
20-05-2014
93.51
3
100
Yes
Yes
Yes
5145
06-00-0969
Kong Sithan
Kampong Thom
(092) 914-384
1/2/2014
1/2/2014
95.36
n/a
No
n/a
5146
06-00-0893
Kam Keng
Kampong Thom
(089) 664-617
11/3/2014
12/6/2014
87.03
3
100
Yes
Yes
Yes
5148
06-00-1035
Heng Sonath
Kampong Thom
(012) 524-063
6/3/2014
3/6/2014
92.59
3
100
Yes
Yes
Yes
5149
06-00-0845
Ieng Keatheng
Kampong Thom
(011) 667-795
18-03-2014
10/6/2014
87.96
3
100
Yes
Yes
Yes
5157
07-00-0143
Ung Chetha
Kampot
(012) 976-371
12/4/2014
12/4/2014
90.74
2.76
92.15
Yes
Yes
Yes
5188
01-00-0068
HENG Vuoch Eng
Banteay Meanchey
(012) 958-919
4/2/2014
28-05-2014
87.96
2.43
81.37
Yes
Yes
Yes
5190
01-00-0123
Nhek Puthary
Banteay Meanchey
(012) 217-175
8/1/2014
22-05-2014
83.33
2.29
76.47
No
Yes
NoWhat SQL Server version you are using? Since SS2012 we have LAST_VALUE function
http://msdn.microsoft.com/en-us/library/hh231517.aspx
SELECT * FROM
SELECT <columns>,ROW_NUMBER() OVER (PARTITION BY providercode ORDER BY date DESC) rn
) AS Der WHERE rn=1
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Hi,
I have a time dimension with levels AllTime, Year, Month, Week, Day. I set the chronological key to the day and created an Ago Measure in my fact. The repository global consistency was successful. However when I used it in answers, I got the following error message:
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 22040] To use AGO function, the storage level of the query ('[DIM_DATE.DIMENSION_KEY]') must be a static level. (HY000)
SQL Issued: SELECT DIM_DATE.CALENDAR_YEAR_NAME saw_0, F_TEST.MEASURE saw_1, F_TEST.YearAgoMeasures saw_2 FROM WMS ORDER BY saw_0
Does anyone have any idea please? Note that the DIM_DATE.DIMENSION_KEY is the primary key of the time dimension table.
Thanks a lot
MarijaHi Wildmight,
I restarted everything and got the "must be a static level. (HY000)" error fixed. Then I checked the chronological key in the level "year" but it seems not to be working. It's taking a long long time to show the results (I finally cancel it).
Reviewing the nqquery log file, I don't really get how obi retrieves the todate info, it uses the analytic function: ROW_NUMBER() OVER (partition by....), do you get the same?
Thanks again. -
PL/SQL function body returning SQL Query Problem
I have wandered around the forums and found quite a bit of helpful information that has gotten me to the point I am now at. Unfortuntely, PL/SQL is not my strongest point and I am getting an error when I attempt to run my report.
This is what I have for my package:
CREATE OR REPLACE PACKAGE LIB2.report_query
is
function create_report2(v1 IN varchar2) RETURN VARCHAR2;
end report_query;
CREATE OR REPLACE PACKAGE BODY LIB2.report_query
as
function create_report2(v1 in varchar2) return varchar2
is
l_vc_format HTMLDB_APPLICATION_GLOBAL.VC_ARR2 := HTMLDB_UTIL.STRING_TO_TABLE(v1);
l_format varchar2(255) := HTMLDB_UTIL.TABLE_TO_STRING(l_vc_format);
q1 varchar2(32767) := ' ';
begin
q1 :=
'select b.BOOK_ID, bk.book_id bkid, bkk.book_id bkkid, b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME, b.ISBN, f.FORMAT_RET, b.DESCRIPTION, .PUBLISHED,'
||'b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE, c.LENGTH_MINS, stragg(p.last_name || '', '' || p.first_name) Author, '
||'stragg(p.person_id) person_id, '
||'pb.name PUBLISHER, decode(b.abridged, ''Y'',''Abridged'',''N'',''Unabridged'') Abridged,'
||'(nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)+nvl(d.disk04,0)+nvl(d.disk05,0)+nvl(d.disk06,0)+nvl(d.disk07,0)+nvl(d.disk08,0)+'
||'nvl(d.disk09,0)+nvl(d.disk10,0)+nvl(d.disk11,0)+nvl(d.disk12,0)+nvl(d.disk13,0)+nvl(d.disk14,0)+nvl(d.disk15,0)+nvl(d.disk16,0)+nvl(d.disk17,0)+'
||'nvl(d.disk18,0)+nvl(d.disk19,0)+nvl(d.disk20,0)+nvl(d.disk21,0)+nvl(d.disk22,0)+nvl(d.disk23,0)+nvl(d.disk24,0)+nvl(d.disk25,0)+nvl(d.disk26,0)+'
||'nvl(d.disk27,0)+nvl(d.disk28,0)+nvl(d.disk29,0)+nvl(d.disk30,0)+nvl(d.disk31,0)+nvl(d.disk32,0)+nvl(d.disk33,0)+nvl(d.disk34,0)+nvl(d.disk35,0)+'
||'nvl(d.disk36,0)+nvl(d.disk37,0)+nvl(d.disk38,0)+nvl(d.disk39,0)+nvl(d.disk40,0)+nvl(d.disk41,0)+nvl(d.disk42,0)+nvl(d.disk43,0)+nvl(d.disk44,0)+'
||'nvl(d.disk45,0)+nvl(d.disk46,0)+nvl(d.disk47,0)+nvl(d.disk48,0)+nvl(d.disk49,0)+nvl(d.disk50,0)) total_tracks'
||'from book b, '
||'book bk,'
||'book bkk,'
||'person p,'
||'lkup_book_author la,'
||'lkup_book_publisher lp,'
||'lkup_book_format lkf,'
||'format f,'
||'publisher pb,'
||'conversion_info_audio c,'
||'lkup_book_disk_info d'
||'where b.book_id = la.book_id'
||'and b.book_id = bk.book_id'
||'and b.book_id = bkk.book_id'
||'and p.person_id = la.author_id'
||'and b.book_id = lp.book_id'
||'and b.book_id = c.book_id'
||'and b.book_id = d.book_id'
||'and b.book_id = lkf.book_id'
||'and lkf.format_id = f.format_id'
||'and pb.publisher_id(+) = lp.publisher_id'
||'and b.wishlist = ''N'''
||'and (upper(b.book_id) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.title) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.subtitle) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.series) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.volume) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.isbn) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.format) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.description) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.published) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.purchased_from) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.comments) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.website) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(p.last_name) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(p.first_name) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(pb.name) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(:P40_SEARCH) is null)'
||'and ((upper(b.title) like ''%'' || upper(:P40_TITLE) || ''%'' or upper(:P40_TITLE) is null))'
||'and ((upper(b.series) like ''%'' || upper(:P40_SERIES) || ''%'' or upper(:P40_SERIES) is null))'
||'and ((upper(p.last_name) like ''%'' || upper(:P40_LASTNAME) || ''%'' or upper(:P40_LASTNAME) is null))'
||'and ((upper(p.first_name) like ''%'' || upper(:P40_FIRSTNAME) || ''%'' or upper(:P40_FIRSTNAME) is null))'
||'and ((upper(f.format_ret) in (upper(l_vc_format)) or upper(:P40_FORMAT) is null))'
||'group by b.BOOK_ID, bk.book_id, bkk.book_id, b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME, b.ISBN, f.FORMAT_ret, b.DESCRIPTION, '
||'b.PUBLISHED, b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE, c.LENGTH_MINS, pb.name, b.abridged, '
||'(nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)+nvl(d.disk04,0)+nvl(d.disk05,0)+nvl(d.disk06,0)+nvl(d.disk07,0)+nvl(d.disk08,0)+'
||'nvl(d.disk09,0)+nvl(d.disk10,0)+nvl(d.disk11,0)+nvl(d.disk12,0)+nvl(d.disk13,0)+nvl(d.disk14,0)+nvl(d.disk15,0)+nvl(d.disk16,0)+nvl(d.disk17,0)+'
||'nvl(d.disk18,0)+nvl(d.disk19,0)+nvl(d.disk20,0)+nvl(d.disk21,0)+nvl(d.disk22,0)+nvl(d.disk23,0)+nvl(d.disk24,0)+nvl(d.disk25,0)+nvl(d.disk26,0)+'
||'nvl(d.disk27,0)+nvl(d.disk28,0)+nvl(d.disk29,0)+nvl(d.disk30,0)+nvl(d.disk31,0)+nvl(d.disk32,0)+nvl(d.disk33,0)+nvl(d.disk34,0)+nvl(d.disk35,0)+'
||'nvl(d.disk36,0)+nvl(d.disk37,0)+nvl(d.disk38,0)+nvl(d.disk39,0)+nvl(d.disk40,0)+nvl(d.disk41,0)+nvl(d.disk42,0)+nvl(d.disk43,0)+nvl(d.disk44,0)+'
||'nvl(d.disk45,0)+nvl(d.disk46,0)+nvl(d.disk47,0)+nvl(d.disk48,0)+nvl(d.disk49,0)+nvl(d.disk50,0))';
RETURN q1;
EXCEPTION
WHEN OTHERS THEN
RETURN q1;
end create_report2;
end;
And here is what I have for my Region Source on my report:
return lib2.report_query.create_report2(v('P40_FORMAT'));
Here is my error when I run the page:
failed to parse SQL query:
ORA-00936: missing expression
I have tried the region source line in many variations, this is just my latest one. None of them have worked. I am quite obviously missing something quite important and probably extremely silly. Any ideas?
Thanks!
ChrissyChrissy,
This is what the package returns as a query:
select b.BOOK_ID, bk.book_id bkid, bkk.book_id bkkid,
b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME, b.ISBN, f.FORMAT_RET,
b.DESCRIPTION, .PUBLISHED,b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE,
c.LENGTH_MINS, stragg(p.last_name || ', ' || p.first_name) Author,
stragg(p.person_id) person_id, pb.name PUBLISHER, decode(b.abridged,
'Y','Abridged','N','Unabridged') Abridged,
(nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)+nvl(d.disk04,0)+nvl(d.disk05,0)
nvl(d.disk06,0)nvl(d.disk07,0)+nvl(d.disk08,0)+nvl(d.disk09,0)+nvl(d.disk10,0)
nvl(d.disk11,0)nvl(d.disk12,0)+nvl(d.disk13,0)+nvl(d.disk14,0)+nvl(d.disk15,0)
nvl(d.disk16,0)nvl(d.disk17,0)+nvl(d.disk18,0)+nvl(d.disk19,0)+nvl(d.disk20,0)
nvl(d.disk21,0)nvl(d.disk22,0)+nvl(d.disk23,0)+nvl(d.disk24,0)+nvl(d.disk25,0)
nvl(d.disk26,0)nvl(d.disk27,0)+nvl(d.disk28,0)+nvl(d.disk29,0)+nvl(d.disk30,0)
nvl(d.disk31,0)nvl(d.disk32,0)+nvl(d.disk33,0)+nvl(d.disk34,0)+nvl(d.disk35,0)
nvl(d.disk36,0)nvl(d.disk37,0)+nvl(d.disk38,0)+nvl(d.disk39,0)+nvl(d.disk40,0)
nvl(d.disk41,0)nvl(d.disk42,0)+nvl(d.disk43,0)+nvl(d.disk44,0)+nvl(d.disk45,0)
nvl(d.disk46,0)nvl(d.disk47,0)+nvl(d.disk48,0)+nvl(d.disk49,0)+nvl(d.disk50,0)) total_tracksfrom book b,
book bk,book bkk,person p,lkup_book_author la,lkup_book_publisher lp,
lkup_book_format lkf,format f,publisher pb,conversion_info_audio c,
lkup_book_disk_info dwhere b.book_id = la.book_idand b.book_id = bk.book_idand b.book_id = bkk.book_idand p.person_id = la.author_idand
b.book_id = lp.book_idand b.book_id = c.book_idand b.book_id = d.book_idand
b.book_id = lkf.book_idand lkf.format_id = f.format_idand pb.publisher_id(+) = lp.publisher_idand
b.wishlist = 'N'and (upper(b.book_id) like '%' || upper(:P40_SEARCH) || '%'
or upper(b.title) like '%' || upper(:P40_SEARCH) || '%'or upper(b.subtitle) like '%' ||
upper(:P40_SEARCH) || '%'or upper(b.series) like '%' || upper(:P40_SEARCH) || '%'or
upper(b.volume) like '%' || upper(:P40_SEARCH) || '%'or upper(b.isbn) like '%' ||
upper(:P40_SEARCH) || '%'or upper(b.format) like '%' || upper(:P40_SEARCH) || '%'or upper(b.description) like '%' || upper(:P40_SEARCH) || '%'or upper(b.published)
like '%' || upper(:P40_SEARCH) || '%'or upper(b.purchased_from) like '%' ||
upper(:P40_SEARCH) || '%'or upper(b.comments) like '%' || upper(:P40_SEARCH)
|| '%'or upper(b.website) like '%' || upper(:P40_SEARCH) || '%'or
upper(p.last_name) like '%' || upper(:P40_SEARCH) || '%'or upper(p.first_name)
like '%' || upper(:P40_SEARCH) || '%'or upper(pb.name) like '%' ||
upper(:P40_SEARCH) || '%'or upper(:P40_SEARCH) is null)and
((upper(b.title) like '%' || upper(:P40_TITLE) || '%' or
upper(:P40_TITLE) is null))and ((upper(b.series) like '%' ||
upper(:P40_SERIES) || '%' or upper(:P40_SERIES) is null))and
((upper(p.last_name) like '%' || upper(:P40_LASTNAME) || '%' or
upper(:P40_LASTNAME) is null))and ((upper(p.first_name) like '%' ||
upper(:P40_FIRSTNAME) || '%' or upper(:P40_FIRSTNAME) is null))and
((upper(f.format_ret) in (upper(l_vc_format)) or upper(:P40_FORMAT) is null))
group by b.BOOK_ID, bk.book_id, bkk.book_id, b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME,
b.ISBN, f.FORMAT_ret, b.DESCRIPTION, b.PUBLISHED, b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE,
c.LENGTH_MINS, pb.name, b.abridged, (nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)
nvl(d.disk04,0)nvl(d.disk05,0)+nvl(d.disk06,0)+nvl(d.disk07,0)+nvl(d.disk08,0)
nvl(d.disk09,0)nvl(d.disk10,0)+nvl(d.disk11,0)+nvl(d.disk12,0)+nvl(d.disk13,0)
nvl(d.disk14,0)nvl(d.disk15,0)+nvl(d.disk16,0)+nvl(d.disk17,0)+nvl(d.disk18,0)
nvl(d.disk19,0)nvl(d.disk20,0)+nvl(d.disk21,0)+nvl(d.disk22,0)+nvl(d.disk23,0)
nvl(d.disk24,0)nvl(d.disk25,0)+nvl(d.disk26,0)+nvl(d.disk27,0)+nvl(d.disk28,0)
nvl(d.disk29,0)nvl(d.disk30,0)+nvl(d.disk31,0)+nvl(d.disk32,0)+nvl(d.disk33,0)
nvl(d.disk34,0)nvl(d.disk35,0)+nvl(d.disk36,0)+nvl(d.disk37,0)+nvl(d.disk38,0)
nvl(d.disk39,0)nvl(d.disk40,0)+nvl(d.disk41,0)+nvl(d.disk42,0)+nvl(d.disk43,0)
nvl(d.disk44,0)nvl(d.disk45,0)+nvl(d.disk46,0)+nvl(d.disk47,0)+nvl(d.disk48,0)
nvl(d.disk49,0)nvl(d.disk50,0))
This query will never work. I marked only couple of errors you have there. Actually,
I meant "formating" errors rather than "syntactical" errors. You are missing spaces
all over the place. This is why I suggested to use a CLOB column in a test table
to return the query for debugging purposes - this is how I do it at least, when I need
to escape and concatenate a lot of code.
If you are referencing item values from a user session in a function or a procedure,
then you need to use the v('ITEM') syntax instead of :ITEM syntax. However, if the
output of this procedure will be used as a function returning SQL query, you will
be fine with :ITEM.
Denes Kubicek
http://deneskubicek.blogspot.com/
http://htmldb.oracle.com/pls/otn/f?p=31517:1
-------------------------------------------------------------------
Maybe you are looking for
-
Any idea's guys????
-
9I STATSPACK PACKAGE를 이용하여 생성된 성능보고서 분석 예제
제품 : ORACLE SERVER 작성날짜 : 2005-01-07 9I STATSPACK PACKAGE를 이용하여 생성된 성능보고서 분석 예제 ========================================== PURPOSE 이 문서는 9i 데이타베이스 운영 중 전반적인 System performance 저하를 경험할 경우 StatsPack Package를 이용하여 성능관련 문제 분석에 활용하는 방법을 예제를 통해 알아보기로 한다. E
-
Not able to clear open item. Error payment block
Hi, When I am trying to clear an open item for a customer, I am getting this error message "1 item(s) was/were not activated due to online payment block ". I checked v_t008 and could see that 'Manual Payments block is enabled for Block Ind 'A'. but h
-
On Thursday I downloaded and installed iTunes v8.0. all was working fine after that. On Friday, I installed the new 2.1 version for the iPhone as well as the latest for MobileMe. All appeared to be working fine. About 4 hours later, I docked my iPhon
-
I just burned through 10 dvds and they all look terrible. There are all these wavy lines. Is this a field order problem? If so, how do I correct it. I have missed my deadline and I am in big trouble. Please help. Thanks