Displaying count(*) in the cursor record
Hi,
I have the following cursor:
CURSOR inputs_cur IS
SELECT a, b, COUNT(*) cnt FROM INPUTS
GROUP BY a, b
ORDER BY COUNT(*) DESC;
inputs_rec inputs_cur%ROWTYPE;
BEGIN
OPEN inputs_cur;
LOOP
FETCH inputs_cur INTO inputs_rec;.
How can I reference count(*) in the cursor record?
d_str := inputs_rec.a || ' ' || inputs_rec.b || inputs_rec.cnt ( or cnt) ???
inputs_rec.cnt ( or cnt) does not display any data....
Thanks
Ia
SQL> Declare
2 Cursor C1 is Select a.c1 col1,count(*) col2 from
3 (Select 1 c1 from dual connect by rownum<=10
4 union all
5 Select 2 c1 from dual connect by rownum<=20) a
6 Group by a.c1;
7 abc c1%rowtype;
8 begin
9 Open C1;
10 loop
11 Fetch C1 into abc;
12 exit when C1%NOTFOUND;
13 dbms_output.put_line('Record Value: ' || abc.col1);
14 dbms_output.put_line('Count of record: ' || abc.col2);
15 end loop;
16 end;
17 /
Record Value: 1
Count of record: 10
Record Value: 2
Count of record: 20
PL/SQL procedure successfully completed.
SQL>
Similar Messages
-
How to determine the cursor record count before the "open cursor"?
Is it possible to determine the record count of an explicit cursor without running a count()? Say, my cursor definition is something like this,
CURSOR cur_vehicle
IS
SELECT os.order_id, os.order_item, vs.part_id
vs.part_num,
vs.iso_num,
vs.model_yr
vs.dealer_cde,
vs.cust_cde,
px.plant_cd
FROM parts_source vs,
orders_source os,
plant_tbl_crossref px
wHERE os.order_id = vs.order_id
AND vs.part_id = os.part_id
AND vs.plant_cde = px.plant_cde
ORDER BY os.order_id;
I want to log the count of records returned by the above cursor prior to the first fetch, without running a count(1) for the query in cursor select.
I know adding " Count(1) over(order by null) " in the cursor SELECT will bring it. But that does not help me log the record count to some log file or table before opening the cursor for processing.
To conclude, my objective is to update the record count of cursor in some table before processingsarvan wrote:
Is it possible to determine the record count of an explicit cursor without running a count()?
..snipped..No. The only way to do it correctly is inside that select.
Each select is a consistent read. Which means that if this is done as 2 select statements, the 1st select can see a different version of the data than the 2nd select statement. does. So if you want a count and that to be consistent and on the same version of the data than the select, it has to be done as part of the select.
Also consider what a cursor is. It is not a result set of sorts that is created in memory upfront - with a convenient interface that tells you the size/number of rows of that result set.
A cursor is basically a program that reads database data as input and produce output. A fetch from a cursor is an instruction for this program to execute and output data.
There's no data set that is created by the cursor from which the count can be determined. The cursor program does have state variables - like +%RowCount+ that specifies how many rows the cursor has thus far output. And you need to run that cursor to the end (no more output) in order to determine the total number of rows output by the cursor. -
SQ01 - SAP List Viewer - Ability to get the count of the output records
Hello All,
I have a problem with the SAP List Viewer output for an SAP Query.
I have created a SAP query (SQ01) for a table. Its a basic query that queries on just one table (VTBFHA)
When I run the query, for the output in the SAP List Viewer (ALV) format, Could anyone kindly help me figure out how to get the count of the number of records displayed in the output?
For Eg: when we run the T code SE16, It gives us the number of records displayed in the output.
Similarly, does anyone know if there is a way I could display the count of the number of records displayed in the output of the SQ01 query?
I have tried checking the "Counter" in the basic list tab, but it does not give me the count.
Any help will be greatly appreciated
Thanks
SubhaniYes there is a solution. Follow these steps
Select your query
Hit the button InfoSet Query
Go to Edit->Settings->
Check the box "Count in the Output list" in the Output tab
Hit Save
In pop up box select the user group
hit enter
Hit the back arrow (F3)
now Execute the query
You should be able to see the count in the output.
The count will appear on the right most column of the output. If it does not go to the "Change layout" option and make sure it is part of the "Displayed columns list".
Regards -
Query to display multiple counts in the result
Hi,
I need to be able to display multiple counts for different items in the single result set:
Here is the simplified schema:
I have 2 tables:
STATEMENT table:
===============
statement_pk number,
department varchar2(20)
STATEMENT_INFO table:
===================
statement_info_pk number,
statement_fk number
is_statement_done varchar2(1)
is_statement_locked varchar2(1)
I need to display counts of how many records where done and how records where locked in the
single output:
Statement_PK Department NumberOfStatementsDone# NumberofStatementsLocked#
1 ABC_dept 3 5
2 DEF_dept 4 8
3 XYZ_dept 7 2
The following does not work:
SELECT
s.statement_pk,
s.department,
COUNT(r.statement_info_pk ) NumberOfStatementsDone# ,
COUNT(rr.statement_info_pk ) NumberOfStatementsLocked#
FROM STATEMENT s ,
STATEMENT_INFO r,
STATEMENT_INFO rr
WHERE
s.statement_pk = r.statement_fk
AND s.statement_pk = rr.statement_fk
AND is_statement_done = 'Y' AND rr.is_statement_locked = 'Y'
GROUP BY statement_pk, s.department
I was trying to work with analytic function but could not figured it out either.
Please help
Thanks,
Ia.this would be something like:
SQL> r
1 select statement_pk,
2 department,
3 sum(decode(is_statement_done, 'Y', 1, 0)) statement_done,
4 sum(decode(is_statement_locked, 'Y', 1, 0)) statement_locked
5 from statement_info,
6 statement
7 where statement_fk = statement_pk
8* group by statement_pk, department
STATEMENT_PK DEPARTMENT STATEMENT_DONE STATEMENT_LOCKED
1 ABC_dept 4 1
2 DEF_dept 6 2
3 XYZ_dept 1 2
SQL> Message was edited by:
Leo Mannhart
Craig you were faster -
How can I change the numeric format of the cursor coordinates display in LV 8.2
Since LV 8.0 or so the cursor display window of a graph indicator seems to be a tree control. I couldn't find where to change the numeric format of the numbers displayed in that control. What did I miss?
lecroy wrote:
Maybe I'm not clear on what your looking for but I just use a property node and route the raw cursor data out to what ever function I want to run on it, then display it in a seperate field. The nice thing with the property node is you can have multiple graphs linked together by one set of cursors all with different readouts.
Yes, of course that's an option and I guess I'll have to do it that way.
The point is that I converted a pre-LV-8.x program to LV 8.5. In the program I had used the coordinates display field in the cursor legend to display the position, just the was the cursor legend is supposed to be used, IMO. And in pre-LV-8.x days it was possible to customize the numeric format property of the cursor legend (either directly or by property nodes). It seems that with LV 8.x NI chose to use a treeview control for the cursor legend. With that 'improvement' the numeric formatting flexibility was lost since now the conversion to the string content in the cursor legend's treeview is happening somewhere 'under the hood'.
<rant> Why do they (NI) always try to 'improve' things (where nothing needs be improved) and sacrifice functionality on the way....? </rant> -
How to get the total record count for the report
Hi,
How can I get count of the total records shown in the report. When we set the report attributes, we have an option "Set Pagination from X to Y of Z"
Does anyone know how can I get the Z value from APEX variables.
I know we can use that query and get the count but I just want to know how we can use APEX Variables effectively.
Thanks in advance.You write a loop, something like this:
Go_block('B1');
If not form_success then
Raise Form_Trigger_failure;
End if;
First_Record;
If not form_success then
Raise Form_Trigger_failure;
End if;
Loop
If :system.record_status in('CHANGED','INSERT') then
-- modify the record here--
End if;
Exit when :System.Last_Record = 'TRUE';
Next_Record;
End Loop;
First_Record;But be very careful-- If your block can fetch a large number of rows, (over 100), this loop can take a long time, and you should not use this method. The loop will continue fetching more rows from the database until all rows satisfying the query are retrieved. -
PLSQL and XMLTYPE -- Trying to pass cursor record into a XMLTYPE query.
Hi all --
I'm trying to pass records from a cursor into a xmltype query, with no success. If i hard code what the cursor record is, it works just fine, but when I use cursor_rec.value, I think it is taking that strin literally. Here is a simple example of what i'm trying to do.
Brief Background -- I have two tables (OPLAN, OPLAN_SUB_CONT) with an XMLTYPE column. OPLAN contains the bulk/main XML with about 30 elemets, while OPLAN_SUB_CONT contains the xml files which either inserts or updates any of the 30 elements. Instead of hard coding 30 statments to check each element, I created a cursor to cycle through the possible elements. If an element exists i do something , if not i go the next element.
This returns null, using elements_rec.element_name in the query...
declare
cursor cur_get_elements is
select element_name
from oplan_element_attribs
where parent_element='Transactions'
and element_name='OPLAN_STATUS';
elements_rec cur_get_elements%rowtype;
v_element number;
begin
for elements_rec in cur_get_elements
Loop
dbms_output.put_line ('before extract');
select nvl(count(value(p)),0)
into v_element
from oplan_sub_content_xml oscx,
table(xmlsequence(extract(SUBSCRIPTION_CONTENT,'Transactions/elements_rec.element_name'))) p;
if v_element =0
then dbms_output.put_line ('Element ' || elements_rec.element_name || ' is null');
elsif v_element > 0
then dbms_output.put_line ('Element ' || elements_rec.element_name || ' is not null');
end if;
end loop;
end;
SQL> /
before extract
Element OPLAN_STATUS is null
PL/SQL procedure successfully completed.
If i hard code the element_name (elements_rec.element_name) on line 16 (line wraps) to "OPLAN_STATUS' i get desired results ... returns not null
declare
cursor cur_get_elements is
select element_name
from oplan_element_attribs
where parent_element='Transactions'
and element_name='OPLAN_STATUS';
elements_rec cur_get_elements%rowtype;
v_element number;
begin
for elements_rec in cur_get_elements
Loop
dbms_output.put_line ('before extract');
select nvl(count(value(p)),0)
into v_element
from oplan_sub_content_xml oscx,
table(xmlsequence(extract(SUBSCRIPTION_CONTENT,'Transactions/OPLAN_STATUS'))) p;
if v_element =0
then dbms_output.put_line ('Element ' || elements_rec.element_name || ' is null');
elsif v_element > 0
then dbms_output.put_line ('Element ' || elements_rec.element_name || ' is not null');
end if;
end loop;
end;
SQL> /
before extract
Element OPLAN_STATUS is not null
PL/SQL procedure successfully completed.
Any ideas?
Thanks!I should try everything before posting! Sorry, got it to work...
replaced ..
select nvl(count(value(p)),0)
into v_element
from oplan_sub_content_xml oscx,
table(xmlsequence(extract(SUBSCRIPTION_CONTENT,'Transactions/elements_rec.element_name'))) p;
with
select nvl(count(value(p)),0)
into v_element
from oplan_sub_content_xml oscx,
table(xmlsequence(extract(SUBSCRIPTION_CONTENT,'Transactions/' || elements_rec.element_name || ''))) p; -
I try to display a number of executed record on the forms screen.
I try to display a number of executed record on the forms screen
while a cursor loop statement is running. (the cursor statement is in server)
And i used the 'when-timer-expired' trigger in forms developer.
it was possible to update the count of executed record to a temporary table,
but it didn't work to dislay the result on the forms in real-time .
only on time the trigger was executed when the cursor loop was finished.
Does anyone know the method of showing the count in real-time???
Message was edited by:
조현정
Message was edited by:
조현정If I understand you:
- You created a procedure in the database that uses a cursor to process one record at a time.
- This procedure updates a temp table that indicates the current record being processed.
- While the procedure is running you created a repeat timer that queries the temp table and displays in the form the current record being processed.
Now, you say that the timer only executed once after the database procedure was finished. Is that your problem?
If so, I think you may have to start the procedure using the database scheduler. Then use a repeat timer to query the temp table. Your procedure will need to indicate in the temp table when it is finished so you can stop the timer. (There may be another way to check if the procedure is done. For example, the database may provide some means to indicate that the procedure in scheduler is done.)
Message was edited by:
Mark Roberts -
Commit in a loop of records for the cursor
Hello
my procedure has the following structure
procedure proc2
BEGIN
begin
insert into table A
exception when others
log the error
return
end
begin
insert into table B
exception when others
log the error
return
end
END--end of proc2
--main procedure
open cursor
loop
fetch cursor
proc2
end loop;
commit;
end;-- end of main
my question is do i need to commit inside the loop , also since i have exception handling for all the inserts, if any one of the inserts fails then it should log the error, and go to the next record.., or will it roll back all the previous insert operations since the commit is outside the loop in other words if the there are 10 records in the cursor, and the insert fails at 9th record will oracle roll back all the previous insert operations???
thanks
abhishekmy question is do i need to commit inside the loop ,depends if you want to commit rigth away or if you want to include a counter to check when you want to commit
also since i have exception handling for all the
inserts, if any one of the inserts fails then it
should log the error, and go to the next record.., right
or will it roll back all the previous insert operations
since the commit is outside the loop in other words
if the there are 10 records in the cursor, and the
insert fails at 9th record will oracle roll back all
the previous insert operations???based on your logic if you had exceptions it will skip to the next record -
Php page won't display the first record
I have the following code, but it always skip the first row of the records pull from an Oracle table:
include "utility_functions.php";
// Form the query and execute it
$sql = "select * from dept where cid=".$_GET['q'];
$result_array = execute_sql_in_oracle ($sql);
$result = $result_array["flag"];
$cursor = $result_array["cursor"];
if ($result == false){
display_oracle_error_message($cursor);
die("Client Query Failed.");
// Display the query results
echo "<ul class=\"nav\">";
$values = oci_fetch_array ($cursor);
//echo $values[0];
// Fetch the result from the cursor one by one
while ($values = oci_fetch_array($cursor)){
$did = $values[0];
$dname = $values[1];
echo("<li><a href=\"showdetail.php?did=$did\">$dname</a></li> ");
oci_free_statement($cursor);
echo "</ul>";
for example, I have the following in dept table:
did dname
1 Business
2 Education
3 Math
4 English
It will only list: education, math, and english. Any clues?What does execute_sql_in_oracle() do?
Try following example code, such as from:
http://www.php.net/manual/en/oci8.examples.php
http://www.php.net/manual/en/function.oci-fetch-array.php
http://www.php.net/manual/en/function.oci-bind-by-name.php
It's extremely insecure (and slow) to do a query made up with string concatenation like:
$sql = "select * from dept where cid=".$_GET['q'];
You probably need to first sanitize $_GET to remove anything malicious. Then you must use a bind variable on the sanitized result. -
Query in SQL to display count of all records but where condition is present
Hi All,
I have situation where I need to display count of all records all particular period but in where condition type condition has to be present :
Please find the below sample data :
PERIOD_ID TYPE MV_COUNT IS_FLAG
20110401 AM 1 0
20110401 AM 1 0
20110401 MS 29 0
20110501 MS 1 0
20110601 MS 14 0
20110701 MS 2 0
20110401 MS 1 0
20110401 AM 2 0
20110401 AM 69 0
20110401 AM 2 0
finally I need for type = MS
i) total is_flag count for all the periods
ii) for period=20110501 what is the mv_count
I need to use the table single time (ie not self join outer joins )
I have tried to use partition by clause but it will filter out the data .
Cheers,
Sp842106 wrote:
finally I need for type = MS
i) total is_flag count for all the periods
ii) for period=20110501 what is the mv_count
I need to use the table single time (ie not self join outer joins )
I have tried to use partition by clause but it will filter out the data .
select sum(is_flag) is_flg_count,
sum
case when period = 20110501 then mv_count else 0 end
) mv_cnt_for_20110501
from your_table
where type = 'MS'; -
Adhoc Query- Count of no of Records not displayed
Hi,
We are building adhoc queries for one of your requirements. In which, we need to generate the total count of the records. And also no of records with the same value in a specific column.
Even though we configured this value properly, the ALV output is not displayed as per the configuration.
Configurations:
1. Configure a Column in the count field in the "Basic List"
2. And also tried, Configuring Sort Ascending and Sum attributes under the "Statistics" .
None of the above two has produced the desired result.
Can you please suggest me which way we need to go ?Hi,
Before the output in ALV you can try:
1. Total record count - you can try use DESCRIBE TABLE <internal table> LINES <variable>.
2. No. of records with same values - pass the internal table to another internal table and DELETE ADJACENT DUPLICATES COMPARING your needed field, then you can compare the 2 internal table and count number of similar values.
Hope this gave you another way to address your problem.
Thanks.
kath -
Hi,
Can any one kindly tell me how to get the number of records fetched into a REF CURSOR.
ThanksI'll tell you what I'm doing, but I don't like it. After I open the query, I run a count query using the same where and join clauses. The IO cost should be low because the records were accessed in the last statement, but the CPU will still cost you. As an alternative, you could declare a varray of your rowtype and select into that using a BULK COLLECT clause then you could get the count of the varray. I have not tried that yet, but if I ever get the time I will.
The first option looks like this:
OPEN p_Cursor FOR
SELECT MyField1, MyField2
FROM MYTable
INNER JOIN MyTable2 ON ...
WHERE ...
SELECT COUNT(*) INTO p_RowCount
FROM MYTable
INNER JOIN MyTable2 ON ...
WHERE ...
If you find a better way, please post it. -
How to display the NULL records by multiple XMLTABLE()
First, let me provide the testing data of INSERT and CREATE TABLE sql:
create table xml_t2 (xml_raw XMLTYPE);insert sql, a bit long.....just copy and paste then run it will be OK!
the system warns: Your message exceeds the maximum length of 30000 characters.
So, I place it on the mediafire shariing space
http://www.mediafire.com/?npmot6lgl86dgliTesting SQL:
SELECT t1.years, t1.months,t1.days,t1.hours,t1.value,t2.value
FROM xml_t2,
XMLTABLE ('$d/cdata/F1' passing xml_raw as "d" COLUMNS years integer path '//year', months varchar(3) path '//month', days varchar(2) path '//day', hours varchar(2) path '//hour', mins varchar(2) path '//minute', value float path '//value') t1 ,
XMLTABLE ('$d/cdata/F2' passing xml_raw as "d" COLUMNS years integer path '//year', months varchar(3) path '//month', days varchar(2) path '//day', hours varchar(2) path '//hour', mins varchar(2) path '//minute', value float path '//value') t2The condition for now is....In the xml data, I have deleted the month 'Jan' with <F2>tag which is in 2010.
That mean the output of XMLTABLE t2 will not contain the 'Jan' records but it is still remain in XMLTABLE t1.
The problem is that when I use the above SQL to show the t1.value, it will not display the t1.value in 2010 Jan.....it just skipped 'Jan' and becomes 'Feb'...
what i would prefer to display is something like this:
YEARS MONTHS DAYS HOURS t1_value t2_value
2009 Jan 01 01 8 8
2009 Jan 01 02 8 580
2009 Jan 02 01 580 580
2009 Jan 02 02 580 580
2009 Feb 01 01 440 440
2010 Jan 01 01 627 NULL
2010 Jan 01 02 627 NULL
2010 Jan 02 01 367 NULL
2010 Jan 02 02 367 NULL
2010 Feb 01 01 367 849
2010 Feb 01 02 849 849
..............So...the main problem is how to display back the record in JAN in 2010 in t1 XMLTABLE and assign null to the t2 XMLTABLE since it doen't contains this months record.
THANKS for help!!Hi,
What's your database version?
Are you using binary XML storage? (This is the default in 11.2.0.2)
If not you have to explicitely specify it :
create table xml_t2 (xml_raw XMLTYPE)
xmltype column xml_raw store as securefile binary xml;Along with object-relational, it's the best storage strategy to use in conjunction with XMLIndex.
You should also use a structured XML index instead, it's more appropriate than the unstructured index you're currently using :
create index xml_t2_sxi on xml_t2 (xml_raw)
indextype is xdb.xmlindex
parameters (q'#
XMLTABLE xml_t2_xt '/cdata'
COLUMNS
YEARS INTEGER PATH 'F1/name/year',
MONTHS VARCHAR(3) PATH 'F1/name/month',
DAYS VARCHAR(2) PATH 'F1/name/day',
HOURS VARCHAR(2) PATH 'F1/name/hour',
MINS VARCHAR(2) PATH 'F1/name/minute',
VALUE FLOAT PATH 'F1/name/value',
VALUE2 FLOAT PATH 'F2/name/value'
call dbms_stats.gather_table_stats(user, 'XML_T2');Use the query provided by Stew and check the explain plan, you'll see the difference. -
How to get "all the required records" displayed from my DB
Hi,
In a block i have some fields say MONTH, YEAR, STAFF..... and a button SEARCH.
i want, my app user enter data in one or many fields and after clicking SEARCH button he gets all his relevant data from DB (in next window/canvas).
i am using 10g.
help...plz !!!ManiKanchan wrote:
sorry to bother..
(-----version 10g-----)
i have 3 blocks B1, B2, B3.... let the name of my table in DB is TB
in B1, i have a button UPDATE and a trigger, WHEN-BUTTON-PRESSED, attached to it. the pl/sql code here is "go_block('B2'); enter_query;"
when i come to B2 after pressing UPDATE, i am in query mode as i can say...
here in B2, i have 3 fields UNIT, MONTH, YEAR and a button SEARCH. I let user enter 1/2/3 field as he/she wishes
and with search button there is a trigger WHEN-BUTTON-PRESSED with the code "go_block('B3'); execute_query;"
in B3, fields are STAFF, NAME, WAGES, UNIT, MONTH, YEAR.
what i want is,
according to the inputs in B2 ( one or two or all three) , all the relevant records should be displayed on canvas3 ( as B3 fields) as a table
but i am not getting it right..What is the data type of unit,month and year in block b2 and b3 ?
If i think these three are number data type
try this in the search button of block b2
declare
con varchar2(500);
qt varchar2(10):='''';
begin
if :B2.UNIT is not null then
con:='UNIT='||:B2.UNIT;
end if;
if :B2.MONTH is not null then
con:=con||' and MONTH='||:B2.MONTH;
end if;
if :B2.YEAR is not null then
con:=con||' and YEAR ='||:B2.YEAR;
end if;
go_block('b3');
set_block_property('b3',default_where,con);
execute_query;
end;hopes this helps
Maybe you are looking for
-
DW CS6 - Spry collapsible panels - How to have panel close when you click away from it?
I know typically onmouseout is used to close other items, but I could not figure it out with the spry collapsible panel. I have the panel opening onclick and closing onclick, but I would really like for it to close when you click anything else on the
-
Adding row at a table in indesign CS6 from javascript
I have a table in my indesign page.It has one column and several rows. I want to add a row at the begining of the table and add some text content to it. I tried some provided code but none have worked. This is how i reference the table object. var m
-
My Ipod Mini battery drains down without any use. Is this normal. My HP Ipaq 4155 battery does not drain down without any usage. Can anyone help me please. Thanks, Jeff
-
Problems with numeric values in the barcode
Hi I have a problem with the data from a numeric field, when it is encoded in the barcode the validation pattern seems to be ignored. I have set the validation pattern of the numeric field to be num{9999} And when I enter a value like "0200" it is di
-
Windows Mobile 5.0 Flash 7 Install
I am having trouble acknowleding T&C's and disclaimer whne installing Flash 7 on WM5 on Treo 700W. I can't find a way to accept or agree. Any advice? Is there a desktop version of Flash 7 that can be installed via ActiveSyc? THANKS!!