Can u find (number of rows) + (SELECT * FROM emp) in 1 query?

We have a requirement like this: We need to pass a SQL statement as a SYS_REFCURSOR OUT variable from a SP. Problem is, if the SQL returned 0 rows we have to send 1 row with all NULLS to the SYS_REFCURSOR.
Is there any way to find out the number of rows returned from a SQL without having to put a SELECT COUNT(*) again using the "same" SQL?

Peter:
That only works if the cursor actually returns rows. Consider:
SQL> create table t as
  2  select rownum id, to_char(to_date(rownum, 'J'), 'Jsp') descr
  3  from user_objects
  4  where rownum <= 5;
Table created.
SQL> insert into t select * from t;
5 rows created.
SQL> commit;
Commit complete.
SQL> create function f (p_id in number) return sys_refcursor as
  2     l_cur sys_refcursor;
  3  begin
  4     open l_cur for
  5        select id, descr, count(*) over() cnt
  6        from t
  7        where id = p_id;
  8     return l_cur;
  9  end;
10  /
Function created.
SQL> var cur refcursor
SQL> exec :cur := f(1);
PL/SQL procedure successfully completed.
SQL> print cur
        ID DESCR             CNT
         1 One                 2
         1 One                 2
SQL> exec :cur := f(42);
PL/SQL procedure successfully completed.
SQL> print cur
no rows selectedSince the OP's requirement (or ""solution" coming from someone who misunderstood the concept of cursors") is that "if the SQL returned 0 rows we have to send 1 row with all NULLS to the SYS_REFCURSOR" the analytic count doesn't help.
@OP
The only reliable (for certain definitions of reliable) way would be to consume the first row of the cursor to see if it did in fact return any rows.
However, if the cursor was initally empty, we then need to generate a new cursor with all NULLS to satisfy the request. Not a big deal, as the new cursor would reflect the state of the database at the time of the initial query, even if a qualifying row was inserted and committed between the first query and the second, but it doesn't work the other way around.
If I consume the first row and find a record, then I need to re-do the query to get all of the rows. but what happens if another process changes/deletes the qualifying row in between and commits? The second query will have no rows and you will return an empty cursor to the caller.
Also, counting the rows (which the analytic count will need to do) could have a significant impact on performance since all the qualifying rows need to be read before the first row can be returned.
John

Similar Messages

  • How to control the number of rows selected from a sybase database table?

    Hi, JDBC guru,
    I'm working on project using Sybase 11.9.x database.We need to process a record in a table,first select it from the table,then do some computing,finally write it to a dbf file, if the above steps succeed,remove the original row in the table.Quite evidently, all these operation should be put into one transaction. But how can I select just a number of rows from the sybase database table?
    Any hints?
    Thank you in advance.
    Regards,
    Jusitne

    Statement stmt...
    stmt.setMaxRows(20);

  • How can I find number of columns in a table using a query

    Hi
    I want to find the number of columns in a table using a query.
    Any help in this regard is much appreciated.
    Cheers

    Hi,
    This is the output i get when i executed ur query
    OWNER     OBJECT_NAME     OBJECT_TYPE
    SMLDBO     T2311_SURVEY_QUESTIONS     TABLE
    select OWNER,OBJECT_NAME,OBJECT_TYPE
    from all_objects
    where OBJECT_NAME = 'T2311_SURVEY_QUESTIONS';
    works Fine.
    But if i use the below query it returns : 0
    SELECT count(*) FROM user_tab_columns
    WHERE table_name =upper( 'T2311_SURVEY_QUESTIONS');
    What could be problem.
    The table exists + name of the table is correct + it resides in my schema itself.
    Any guess !!!

  • Count the number of rows resulting from a select statement

    Hi,
    Is there any way of counting the number of rows resulting from a select statement. i.e I have a select distinct statement and I then want to perform an IF statement on the number of rows resulting from the select statement.
    Any help appreciated
    Thanks
    Gary

    Declare
    var1 number;
    Begin
    select count(distinct column_name) into
    var1 from table_name;
    If var1 > x Then
    End IF;
    End;
    Hope I understood the problem correctly
    null

  • Find number of rows in  a cursor

    How can i find how many rows are in a cursor. I have a situation if my cursor only retruns one row i return the data if it returns more then one row i will need to do additional select.

    If you have logic like this
    SELECT COUNT(*)
      INTO l_cnt
      FROM emp
    WHERE deptno = p_deptno;
    IF( l_cnt > 1 )
    THEN
      FOR x IN (SELECT * FROM emp WHERE deptno = p_deptno)
      LOOP
        ..where you are counting the rows and then later fetching them, getting the count and then getting the rows will force Oracle to do the work of the query twice. It will also potentially cause logic errors because the number of rows returned by the COUNT(*) won't necessarily match the number of rows fetched from the cursor because some other session may have committed changes between your session executing those two statements.
    Can you describe the logic you are trying to implement in a bit more detail? There are potentially a number of different approaches depending on exactly what you are trying to do. Sometimes it may make sense to do a COUNT(*), sometimes it may make sense to fetch the data into a collection, count the collection elements, and then operate on the collection, sometimes it may make sense to do a SELECT INTO and handle the exception if the wrong number of rows are returned, etc.
    Justin

  • How to find number of rows in a table

    i have one table ,it contains millions of record,how can i know number of rows in that table without using count(*),
    i tried in user_table ,for the column NUM_ROWS,but it is not showing number of rows,pls send me a solution for this.
    regards,
    singh

    Ok, that only was to show simply that max option
    might not an option to reduce execution time.Yes, but I/O variances have a tendency to really skew the observed elapsed execution time - making execution time alone a poor choice to determine what SQL will perform better than another.
    Both MAX(ROWNUM) and COUNT(*) results in the same amount of I/O - as both uses the exact same execution plan, I/O wise. In this example, a FTS.
    SQL> create table testtab nologging as select * from all_objects where rownum < 10001;
    Table created.
    -- warmed up the buffer cache with a couple of SELECTs against TESTAB in order
    -- to discard PIOs from the results
    SQL> set autotrace on
    SQL> select count(*) from testtab;
    COUNT(*)
    10000
    Execution Plan
    Plan hash value: 2656308840
    | Id | Operation | Name | Rows | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 35 (9)| 00:00:01 |
    | 1 | SORT AGGREGATE | | 1 | | |
    | 2 | TABLE ACCESS FULL| TESTTAB | 9262 | 35 (9)| 00:00:01 |
    Note
    - dynamic sampling used for this statement
    Statistics
    0 recursive calls
    0 db block gets
    131 consistent gets
    0 physical reads
    0 redo size
    223 bytes sent via SQL*Net to client
    238 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed
    SQL> select max(rownum) from testtab;
    MAX(ROWNUM)
    10000
    Execution Plan
    Plan hash value: 2387991791
    | Id | Operation | Name | Rows | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 1 | 35 (9)| 00:00:01 |
    | 1 | SORT AGGREGATE | | 1 | | |
    | 2 | COUNT | | | | |
    | 3 | TABLE ACCESS FULL| TESTTAB | 9262 | 35 (9)| 00:00:01 |
    Note
    - dynamic sampling used for this statement
    Statistics
    0 recursive calls
    0 db block gets
    131 consistent gets
    0 physical reads
    0 redo size
    225 bytes sent via SQL*Net to client
    238 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed
    So seeing that we have the exact same baseline for both queries, and that PIO does not influence the results, we time a 1000 executions of both.
    SQL> declare
    2 cnt number;
    3 begin
    4 for i in 1..1000
    5 loop
    6 select count(*) into cnt from testtab;
    7 end loop;
    8 end;
    9 /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:03.19
    SQL>
    SQL> declare
    2 cnt number;
    3 begin
    4 for i in 1..1000
    5 loop
    6 select max(rownum) into cnt from testtab;
    7 end loop;
    8 end;
    9 /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:15.87
    SQL>
    This shows that what makes the MAX() more expensive is just that - determining the MAX(). For each row, Oracle has to call its internal MAX() function with two values - the current max result and the new value. This function then returns the new max value. This overhead per row adds up to a significant overhead in execution time - making the MAX() approach 5x slower than the COUNT() approach.

  • How to populate a table based on a row selection from another table.

    Hi, i just started to use ADF BC and Faces. Could some one help me or point me a solution on the following scenario .
    By using a search component , a table is being displayed as a search result. If i select any row in the resulted table , i need to populate an another table at the bottom of the same page from another view. These two tables are related by primary key . May i know how to populate a table based on a row selection from another table. Thanks
    ganesh

    I understand your requirement and the tutorial doesn't talk about Association between the views so that you can create a Master-Detail or in DB parlance, a Parent-Child relationship.
    I will assume that we are dealing with two entities here: Department and Employees where a particular Department has many Employees and hence a Parent-Child relationship.
    Firstly, you need to create an Association between the two Entities - Department and Employees. You can do that by right clicking on the model's entity and then associating the two entities with the appropriate key say, DepartmentId.
    Once you have done that, you need to link the two entities in the View section with this Association that you created. Then go to AppModule and make sure that in the Available View Objects: 'EmployeesView' appears under 'DepartmentView' as "EmployeesView via <link you created>". Shuttle the 'DepartmentView' to the right, Data Model and then shuttle
    "EmployeesView via <link you created>" to the right, Data Model under 'DepartmentView'.
    This will then be reflected in your Data Controls. After that, you simply would have to drag this View into your page as a Master-Detail form...and then when you run this page, any row selected in the Master table, would display the data in the Detail table.
    Also, refer to this link: [Master-Detail|http://baigsorcl.blogspot.com/2010/03/creating-master-detail-form-in-adf.html]
    Hope this helps.

  • How can I reduce number of rows in Planning webform in Smartview?

    Hi,
    I downloaded a Planning webform into Smartview. I want to reduce the 1000 rows down to 20 for a particular user as he does not submit data for the other 980 rows. How can I reduce number of rows in Planning webform in Smartview?
    Someone said that I can insert vlookup code into Smartiveiw pointing to a new worksheet that has only 20 rows. I could not test it as our Planning 9.3.1 has a bug that would not take sub variables from Smartview.
    Thanks.

    Hi,
    My first reaction is why do you have a form with a 1000 rows, surely this is a design issue and doesn't benefit anybody when entering data, anyway why not have security on the dimensions then users will only see what they have access to when they retrieve the form in smart view or through the planning web front end.
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • How do you limit the number of rows return from query?

    How do you limit the number of rows return from query? Do all databases support this kind of feature?

    i think the standard is limit
    to get the top 30
    select * from mytable LIMIT 30;returns the first 30 rows
    also if you want a range
    select * from mytable LIMIT 10,30;returns 30 rows starting from 10
    this last one is useful for displaying ranges... something similar happens in these forums when viewing topics and messages

  • How can I find out the mail server from email address?

    Hi:
    How can I find out the mail server from email address?
    for example: If I know the email address is [email protected],
    how to find the pop3 and smtp mail server?
    THANK YOU

    You can't tell by the email address since you can pretty much put whatever you want in there (especially if the SMTP server is not filtering anything).
    The header may be able to tell you something. There is a Received header value which looks like it has the routing information although I am not sure if this is a complete trace or just the last hop the message took.
    Sean

  • I have photostream turned on on my iPhone, and my macbook and phone are synced. However, I can't find any of the photos from my phone on my computer. Help!

    I have photostream turned on on my iPhone, and my macbook and phone are synced. However, I can't find any of the photos from my phone on my computer. Help!

    Have you looked in iPhoto on your Mac under the "Photo Stream" area shown on the left sidebar?

  • How can I find and remove duplicate photos from my computer?

    How can I find and remove duplicate photos from my computer?

    Terence,
    Yes, the duplicates appear in the iPhoto window. I have folders with same name occuring two or even three times sometimes with exactly the same set of photos (ie photos with the same ID) and sometimes with a limited set of photos. Other  folders appear only once.
    I normally take my MacBook with me if I'm shooting a lot of photos, such as on holiday, and then want to transfer them to my iMac when i get home. Other times I transfer the camera's memory stick directly to my iMac.
    I have great difficulty transferring the photos from my MacBook to my iMac. I don't want to store my photos on my iDisk due to the length of time it takes to upload them.
    Thanks again.
    Simon

  • I can not find "app of the day" from app store on my ipod,how can i find and download it?

    i can not find "app of the day" from app store on my ipod,how can i find and download it?

    It is possible that the app was removed from the App Store. If so you will not be able to get it back, unless you have it downloaded on your computer.
    If you had downloaded it before and it is still in the store, you can go to the App Store app on your iPod and go to the Updates tab. Then you tap on "Purchased" and see if it is available to download from your previous purchases.
    Hope this helps!
    PSkilton

  • Sysdate changes when number of rows selected are huge

    My requirement is that same date and time should be selected for all the rows returned by the query.
    Eg: Select empno, ename , sysdate from Emp
    If the query runs for more than a second, then the second component of SYSDATE will be different.
    What I want is that the query firing time should be selected for all the rows returned by the query.
    I hope there should be a way in Oracle to do this

    Have you actually seen this happen?
    On testing in Oracle 8.1.7i environment with a query
    select col1, col2, to_char(sysdate,'hh24:mi:ss')
    from big_table;
    which returned approx 3m rows and executed for over 8 minutes the sysdate value was the same for the first row selected and the last row selected, and was the time at the start of the query.
    Kevin is correct that Oracle gets the the value of Sysdate once when the query is executed and uses that value until the time that a new query is parsed.
    HTH
    Dave

  • How to find number of rows inserted by dynamic query

    EXECUTE IMMEDIATE l_sql
    USING p_start_date, p_end_date
    RETURN sql%rowcount into l_count;
    Here l_sql is is selecting record from table_1 based on p_start_date, p_end_date and inserting record in table_2.
    There is some further process to be done on table_2 which I want to do only if atleast 1 record is inersted in table_2 by the select query on table_1 for this I am using RETURN sql%rowcount into l_count;
    I am geting error pls-00103 for this.
    Is there any way to achieve this functionality.
    Thanks

    Is there any way to achieve this functionality.Depends on your exact form of l_sql. Here are two ways to get the rowcount out of execute immediate:
    SQL>  create table emp_test as select * from emp where 1=2
    Table created.
    SQL>  begin
       execute immediate 'insert into emp_test select * from emp';
       dbms_output.put_line ('Count: ' || sql%rowcount);
    end;
    Count: 14
    SQL>  rollback
    Rollback complete.
    SQL>  declare
       l_count integer;
    begin
       execute immediate 'begin insert into emp_test select * from emp; :1 := sql%rowcount; end;' using out l_count;
       dbms_output.put_line ('Count: ' || l_count);
    end;
    Count: 14
    PL/SQL procedure successfully completed.

Maybe you are looking for