SQL statement - display expected results

I have this SQL statement:
 SELECT DISTINCT ch.ch_status,cu.customer_id FROM contract co, contract_history ch, customer cu
      WHERE co.co_id = ch.co_id
      AND co.customer_id = cu.customer_id
      AND (cu.passportno= 'S1234567A' ) 
      AND cu.customer_id != 12345
      AND ch.ch_seqno in (SELECT MAX(ch_seqno) FROM contract_history WHERE co_id = co.co_id) 
      and co.co_id IN (SELECT co_id FROM contract_history 
      GROUP BY co_id HAVING(SUM(CASE WHEN ch_status = 'a' AND (ch_status = 'd' or ch_status = 's' or ch_status = 'o') THEN 1 
                                WHEN ch_status = 'a' THEN 1
                                ELSE 0
                                END) > 0))
      ORDER BY decode(ch.ch_status,'d',1,'a',2,'s',3,'o',4)ASC;
With the following results:
CH_STATUS     CUSTOMER_ID
   d                           100
   d                           200
   d                           300
   a                           100
   a                           200
How am I suppose to change my SQL statement in such a way, the results appear only that?

Expected results
CH_STATUS     CUSTOMER_ID
   d                       300
   a                       100
   a                       200
Only the ch_status 'a' is displayed even if it has the status was "too. However, if customer_id has only a status was ', it will be displayed.

I don't get what you're trying to do...

Once you have the slider you can use the cursor... y u still need with clause,...

But yes its possible

QL>
SQL> Declare
  2   Cursor c1 Is
  3   With t As
  4  (
  5  Select 'd' CH_STATUS ,129 CUSTOMER_ID  From dual Union All
  6  Select 'd'           ,62031            From dual Union All
  7  Select 'd'           ,858347           From dual Union All
  8  Select 'a'           ,129              From dual Union All
  9  Select 'a'           ,62031            From dual
 10  ) Select ch_status,customer_id
 11    From
 12  (
 13   Select ch_status, customer_id,
 14          Case When ch_status = 'd' And lag(ch_status) over (Partition By customer_id Order By ch_status) = 'a' Then 0 Else 1 End  new_status
 15   From t
 16   ) Where new_status = 1;
 17
 18   r1 c1%Rowtype;
 19  Begin
 20  Open c1;
 21  Loop
 22  Fetch c1 Into r1;
 23  Exit When c1%Notfound;
 24   dbms_output.put_line(r1.CH_STATUS);
 25  End Loop;
 26  End;
 27  /

a
a
d

PL/SQL procedure successfully completed

SQL> 

Tags: Database

Similar Questions

  • SQL to display the results if the number of output is below a limit

    I have a requirement where I can display the SQL result set if the number of records output is 1000 or less than that... otherwise raise a user-defined exception, say "Please change the search criteria. I can achieve this by GET the the number of SQL rows first and then re-run the same SQL to display the data if the number of rows is less than 1001. Could someone let me know if this is possible without re - run the SQL several times as the SQL is the query intensive re-source

    Hello

    You can try in bulk collect into a collection.

    If the number of rows in the collection is less than 1000 triggers an application error or return results, if it is greater than 1000

    If this is suitable for your needs, please post more information on the system requirements.

    Kind regards

    Cool

  • Cannot display the results to the database during "Update": SQL statement

    Hello

    I get this error trying to update a VO via the UI or BCBrowser.

    Cannot display the results to the database during "Update": SQL statement

    This is a default single front & right THAT VO creates on the object of the entity (Database Table)

    On the same table and with the same credentials of DB, I could update the record.

    Any guess on what went wrong?

    Thanks in advance for any help.

    p.s Jdev 11.1.1.6

    Journal:

    oracle.jbo.DMLException: Houston-26041: could not publish data from database in "Update": SQL statement "START the CAR UPDATED CarEO SET SEL_ITEM =: 1 WHERE TXN_NO =: 2 AND LOGID =: AND SEQNO = 3: 4 POLL DELIVERY_MODE, CERTIFICATION_REQ, SOFT_COPY_IND, SELITEM IN: 5,: 6,: 7,: 8; END; ».

    at oracle.jbo.server.OracleSQLBuilderImpl.doEntityDML(OracleSQLBuilderImpl.java:583)

    at oracle.jbo.server.EntityImpl.doDML(EntityImpl.java:8575)

    at oracle.jbo.server.EntityImpl.postChanges(EntityImpl.java:6816)

    at oracle.jbo.server.DBTransactionImpl.doPostTransactionListeners(DBTransactionImpl.java:3290)

    at oracle.jbo.server.DBTransactionImpl.postChanges(DBTransactionImpl.java:3093)

    at oracle.jbo.server.DBTransactionImpl.commitInternal(DBTransactionImpl.java:2097)

    at oracle.jbo.server.DBTransactionImpl.commit(DBTransactionImpl.java:2378)

    at oracle.adf.model.bc4j.DCJboDataControl.commitTransaction(DCJboDataControl.java:1615)

    at oracle.adf.model.binding.DCDataControl.callCommitTransaction(DCDataControl.java:1417)

    at oracle.jbo.uicli.binding.JUCtrlActionBinding.doIt(JUCtrlActionBinding.java:1437)

    at oracle.adf.model.binding.DCDataControl.invokeOperation(DCDataControl.java:2150)

    at oracle.jbo.uicli.binding.JUCtrlActionBinding.invoke(JUCtrlActionBinding.java:740)

    at oracle.jbo.uicli.jui.JUActionBinding.actionPerformed(JUActionBinding.java:193)

    at oracle.jbo.uicli.controls.JUNavigationBar.doAction(JUNavigationBar.java:412)

    at oracle.jbo.jbotester.NavigationBar.doAction(NavigationBar.java:111)

    to oracle.jbo.uicli.controls.JUNavigationBar$ NavButton.actionPerformed (JUNavigationBar.java:118)

    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)

    in javax.swing.AbstractButton$ Handler.actionPerformed (AbstractButton.java:2318)

    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)

    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)

    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)

    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:272)

    at java.awt.Component.processMouseEvent(Component.java:6289)

    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)

    at java.awt.Component.processEvent(Component.java:6054)

    at java.awt.Container.processEvent(Container.java:2041)

    at java.awt.Component.dispatchEventImpl(Component.java:4652)

    at java.awt.Container.dispatchEventImpl(Container.java:2099)

    at java.awt.Component.dispatchEvent(Component.java:4482)

    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)

    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)

    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)

    at java.awt.Container.dispatchEventImpl(Container.java:2085)

    at java.awt.Window.dispatchEventImpl(Window.java:2478)

    at java.awt.Component.dispatchEvent(Component.java:4482)

    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)

    to java.awt.EventQueue.access$ 000 (EventQueue.java:85)

    in java.awt.EventQueue$ 1.run(EventQueue.java:603)

    in java.awt.EventQueue$ 1.run(EventQueue.java:601)

    at java.security.AccessController.doPrivileged (Native Method)

    in java.security.AccessControlContext$ 1.doIntersectionPrivilege(AccessControlContext.java:87)

    in java.security.AccessControlContext$ 1.doIntersectionPrivilege(AccessControlContext.java:98)

    in java.awt.EventQueue$ 2.run(EventQueue.java:617)

    in java.awt.EventQueue$ 2.run(EventQueue.java:615)

    at java.security.AccessController.doPrivileged (Native Method)

    in java.security.AccessControlContext$ 1.doIntersectionPrivilege(AccessControlContext.java:87)

    at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)

    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)

    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)

    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)

    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)

    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)

    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

    Caused by: java.sql.SQLException: invalid column type

    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:150)

    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:399)

    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:581)

    at oracle.jdbc.driver.OracleCallableStatementWrapper.registerOutParameter(OracleCallableStatementWrapper.java:1765)

    at oracle.jbo.server.OracleSQLBuilderImpl.bindUpdateStatement(OracleSQLBuilderImpl.java:2243)

    at oracle.jbo.server.EntityImpl.bindDMLStatement(EntityImpl.java:10524)

    at oracle.jbo.server.OracleSQLBuilderImpl.doEntityDML(OracleSQLBuilderImpl.java:412)

    ... 52 more

    The problem is solved now.

    new columns added to the database table, after the creation of the entity object. Those changes were not picked up in the entity object.

    I found this difference after object entity with the DB Table comparison.

    And when I added these new columns to EO & VO, I don't get this error more.

    Thanks to all who tried to help

  • Display dynamic SQL statement result

    Hello

    Is it possible to view the sql statement in the procedure below, after that the variables are applied?

    In my view, a solution would be to put the entire statement in an important variable, then use DBMS_OUTPUT. Put_line (my_large_variable) but I'm hoping to save this step.

    Thanks in advance for your help,

    Lou

    create or replace
    PROCEDURE TEST1_PROC)
    p_refcur ON SYS_REFCURSOR,
    p_where in VARCHAR2,
    p_order_by in VARCHAR2
    )

    IS

    v_id ci_summrpt_report_codes.id% TYPE;
    v_descr ci_summrpt_report_codes.descr% TYPE;
    v_valid_flag ci_summrpt_report_codes.valid_flag% TYPE;
    v_order_by VARCHAR2 (100);

    BEGIN
    IF p_order_by IS NULL THEN
    v_order_by: = NULL;
    ON THE OTHER
    v_order_by: = "ORDER BY". p_order_by;
    END IF;
    DBMS_OUTPUT. Put_line (p_where);
    DBMS_OUTPUT. Put_line (v_order_by);
    P_refcur OPEN FOR ' SELECT id, descr, valid_flag OF |
    «(SELECT 1 AS 'ID', "A" AS "DESCR", "Y" AS "VALID_FLAG" OF THE DOUBLE ' |)»
    "UNION ALL" |
    "SELECT 2,"TWO","Y"OF THE DOUBLE ' |
    "UNION ALL" |
    "SELECT 3,"THREE"," Y "DOUBLE" |
    "UNION ALL" |
    SELECT 4, "FOUR", "Y" DOUBLE) ' |
    p_where |
    v_order_by
    ;
    END TEST1_PROC;

    In my view, a solution would be to put the entire statement in an important variable, then use DBMS_OUTPUT. Put_line (my_large_variable) but I'm hoping to save this step.

    This isn't a big problem, I think, is - this? :

    create or replace procedure test1_proc (p_refcur        out sys_refcursor,
                                            p_where      in     varchar2,
                                            p_order_by   in     varchar2)
    is
       v_id           ci_summrpt_report_codes.id%type;
       v_descr        ci_summrpt_report_codes.descr%type;
       v_valid_flag   ci_summrpt_report_codes.valid_flag%type;
       v_order_by     varchar2 (100);
       v_stmt         long;
    begin
       if p_order_by is null
       then
          v_order_by := null;
       else
          v_order_by := ' ORDER BY ' || p_order_by;
       end if;
    
       dbms_output.put_line (p_where);
       dbms_output.put_line (v_order_by);
       v_stmt :=
          'SELECT id, descr, valid_flag FROM '
          || '(SELECT 1 AS "ID", ''ONE'' AS "DESCR", ''Y'' AS "VALID_FLAG" FROM DUAL '
          || 'UNION ALL '
          || 'SELECT 2, ''TWO'', ''Y'' FROM DUAL '
          || 'UNION ALL '
          || 'SELECT 3, ''THREE'',''Y'' FROM DUAL '
          || 'UNION ALL '
          || ' SELECT 4, ''FOUR'',''Y'' FROM DUAL) '
          || p_where
          || v_order_by;
       dbms_output.put_line (v_stmt);
    
       open p_refcur for v_stmt;
    end test1_pro;
    
  • % ROWCOUNT SQL does not return the expected result

    I have the following function within a package:

    --Update APPERY_JTI_deleted_USERS table:
    FUNCTION fn_updt_app_jti_dlt_usr(
        p_update_co      IN VARCHAR2,
        p_appery_user_id IN APPERY_JTI_deleted_USERS.appery_user_id%TYPE,
        p_outlet_code    IN APPERY_JTI_deleted_USERS.outlet_code%TYPE)
      RETURN NUMBER
    AS
    lv_sql       VARCHAR2(4000);
    lv_rowcount  NUMBER := 0;
    BEGIN
    
    lv_sql := 'UPDATE APPERY_JTI_deleted_USERS SET '||p_update_co||' = 1 WHERE '||p_update_co||' = 0 AND OUTLET_CODE = '''||p_outlet_code||''' AND APPERY_USER_ID = '''||p_appery_user_id||'''';
    
    --EXECUTE IMMEDIATE lv_sql;
    EXECUTE IMMEDIATE 'BEGIN ' || lv_sql || '; :z := sql%rowcount; END; ' USING OUT lv_rowcount ;
    
    RETURN lv_rowcount;
      
    EXCEPTION
    WHEN OTHERS THEN
      RETURN -1;  
    END fn_updt_app_jti_dlt_usr;
    
    

    The function called several times as part of a job. Basically, the main function (Say M), call a few functions (for example A1... A9). Each of these functions is to do something and updated the application using the above function. Therefore, each of the nine functions will call the above function with different parameters.

    The problem that I am facing is:

    First run, invoke only first of all for the above function will return the positive result ($sql rowcount > 0). When I run M the second time, only first and second calls for the above function will be to return positive results and so on.

    How odd, it's that if I change the values again and run a function M, it will start from the beginning. And what strange more, the dynamic update statement is executed correctly and data are updated successfully. It's just sql rowcount % do not return is not the expected results.

    I tried to run execute immediately without (begin, end). I also tried to run it without HELP ON. It's always the same. I'm really confused, what Miss me here.

    I don't know if this is relevant. But for what it's worth, invoking the function above updates the SAME lines in the table appery_jti_deleted_users that the columns are different. So for all the work, the same lines need to be updated. Each function (A1... A9) will call the above function to update a different column of these lines.

    If you REALLY want to help you having US SHOW, not tell us:

    1. WHAT you do

    2. HOW to

    3. WHAT results you get

    4. WHAT results you expect to get

    First run, invoke only first of all for the above function will return the positive result ($sql rowcount > 0). When I run M the second time, only first and second calls for the above function will be to return positive results and so on.

    How odd, it's that if I change the values again and run a function M, it will start from the beginning. And what strange more, the dynamic update statement is executed correctly and data are updated successfully. It's just sql rowcount % do not return is not the expected results.

    Perhaps that the foregoing is true and maybe he's not. We have NO WAY of knowing because you don't SHOW US anything.

    I tried to run execute immediately without (begin, end). I also tried to run it without HELP ON. It's always the same.

    Yet once you showed us NOTHING >

    You do NOT FOLLOW best practices when you use dynamic sql statements: the sql statement real so that you can print:

    1 SEE what's running - make sure there are no syntax errors, and it seems to be what you wanted

    2 EXECUTE/TEST manually - to see if he really runs without error and see what results it really give.

    3. FIX any syntax or other problems and retest it

    Instrument properly your code and you won't have the problems you are having.

    You should know by now what are the parameters are transmitted when you run the function. So, there are at least three sets of these parameters.

    So you should be able to:

    1 run the instrumented manually function three times

    2. see that all three SQL statements are

    3 manually run these instructions

    4. see that the number of lines is after each execution

    We have no idea of what the output of the function is every time you call it. Apparently, you have, if you save the results of the function somewhere, but you didn't post any of this info.

    We need real details to help you - just listen to your story is not enough.

  • Cannot display the results in SQL Developer

    Hello Experts - I installed Oracle SQL Developer, just ran simple query. Nothing appears in the results window. Can you please let me know why?

    Select * of the double

    Done «I installed...» "mean you use 4.1.0? Or is it an older version, perhaps even an Early Adopter version? Have you installed in an empty folder? Were there no migration of user settings step?  Did you run the SQL statement (even if it is technically incorrect, as posted here, I guess the Oracle manages Analyzer) using the declaration of implementation (Ctrl + Enter) or run (F5) Script?

    So, you do not have much to do, but...

    1. try to use the latest version of production, installed in an empty folder.  In fact, the 4.1.1 patch comes out.

    2. try to click on the little black down, arrow down to the left of the box of the spreadsheet to see if that exposes a results pane.

    3. try window > Windows reset factory settings if you think that the layout of fenestration of the product is somehow screwed up.

    4. try view > log to see which makes its appearance in the statements of the Log pane tab when you run the SQL (version 4.1.0 & upward).

  • Hide results SQL - State of the button, see the

    Hello
    I use APEX 4.0 with Toad for Oracle 10.5. My problem is that I need to hide the delete button based on the results of the SQL statement. When the point: P43_DEPARTMENT_ID value is entered and there is for any field below, the data will appear along the line.
    SELECT (SELECT distinct department_id
                 FROM tbl_department
                WHERE department_id = :P43_DEPARTMENT_ID
                AND department_id IN (SELECT SUBSTR (division_id, 0, 5)
                                              FROM tbl_division))
                AS DIVISION, 
     (SELECT distinct department_id
                 FROM tbl_department
                WHERE department_id = :P43_DEPARTMENT_ID
                AND department_id IN (SELECT SUBSTR (fk_division_id, 0, 5)
                                              FROM tbl_grant))
                AS GRANTS,     
     (SELECT distinct department_id
                 FROM tbl_department
                WHERE department_id = :P43_DEPARTMENT_ID
                AND department_id IN (SELECT SUBSTR (fk_division_id, 0, 5)
                                              FROM tbl_allotment))
                AS ALLOTMENT,  
     (SELECT distinct department_id
                 FROM tbl_department
                WHERE department_id = :P43_DEPARTMENT_ID
                AND department_id IN (SELECT department_id
                                              FROM tbl_department_temp))
                AS DEPARTMENT_TEMP,
     (SELECT distinct department_id
                 FROM tbl_department
                WHERE department_id = :P43_DEPARTMENT_ID
                AND department_id IN (SELECT SUBSTR (division_id, 0, 5)
                                              FROM tbl_division_temp))
                AS DIVISION_TEMP, 
     (SELECT distinct department_id
                 FROM tbl_department
                WHERE department_id = :P43_DEPARTMENT_ID
                AND department_id IN (SELECT SUBSTR (fk_division_id, 0, 5)
                                              FROM tbl_grant_temp))
                AS GRANT_TEMP,     
     (SELECT distinct department_id
                 FROM tbl_department
                WHERE department_id = :P43_DEPARTMENT_ID
                AND department_id IN (SELECT SUBSTR (fk_division_id, 0, 5)
                                              FROM tbl_allotment_temp))
                AS ALLOTMENT_TEMP
    FROM DUAL
    But when no data appears that there is still a blank line for the fields. That will make the hidden Delete button. I don't know how to remove this row of the grid with my results of the select statement above. The State still thinks there is a line and a value (s) appear statement.
    DIVISION OF | GRANTS | ALLOTMENT | DEPARTMENT_TEMP | DIVISION_TEMP | GRANT_TEMP | ALLOTMENT_TEMP
    ________|_______ |___________|__________________|_____________ |____________|_________________
    Can someone help me with my select statement or provide me with advice on how to remove this blank line when there is no data? I can't create a view and then add a WHERE IS NOT NULL clause because of the variable binding: P43_DEPARTMENT_ID.

    Do not know if I just got it, but what about:

    SELECT SELECT (separate department_id
    OF tbl_department
    WHERE department_id =: P43_DEPARTMENT_ID
    AND department_id IN (SELECT SUBSTR (division_id, 0, 5)
    OF tbl_division))
    THE DIVISION,
    SELECT (separate department_id
    OF tbl_department
    WHERE department_id =: P43_DEPARTMENT_ID
    AND department_id IN (SELECT SUBSTR (fk_division_id, 0, 5)
    OF tbl_grant))
    FORM OF GRANTS,
    SELECT (separate department_id
    OF tbl_department
    WHERE department_id =: P43_DEPARTMENT_ID
    AND department_id IN (SELECT SUBSTR (fk_division_id, 0, 5)
    OF tbl_allotment))
    AS ASSIGNMENT,.
    SELECT (separate department_id
    OF tbl_department
    WHERE department_id =: P43_DEPARTMENT_ID
    AND department_id IN (SELECT department_id
    OF tbl_department_temp))
    AS DEPARTMENT_TEMP,
    SELECT (separate department_id
    OF tbl_department
    WHERE department_id =: P43_DEPARTMENT_ID
    AND department_id IN (SELECT SUBSTR (division_id, 0, 5)
    OF tbl_division_temp))
    AS DIVISION_TEMP,
    SELECT (separate department_id
    OF tbl_department
    WHERE department_id =: P43_DEPARTMENT_ID
    AND department_id IN (SELECT SUBSTR (fk_division_id, 0, 5)
    OF tbl_grant_temp))
    AS GRANT_TEMP,
    SELECT (separate department_id
    OF tbl_department
    WHERE department_id =: P43_DEPARTMENT_ID
    AND department_id IN (SELECT SUBSTR (fk_division_id, 0, 5)
    OF tbl_allotment_temp))
    AS ALLOTMENT_TEMP
    OF THE DOUBLE
    LESS
    SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL from double

    This should ensure you don't receive a "no data found" when all the columns return null.

  • In SQL Developer, is it possible to send the results of a sql statement?

    In SQL Developer, is it possible to send the results of a sql statement?

    Right-click on the query results pane, select "Export data" in the context menu, then select "xls".

  • Retrieve and display a result set using the dynamic sql?

    Hi all

    How would display a result set in Oracle using the dynamic SQL? Reason being, the table where I'd retrieve and display the result set is a GLOBAL TEMP TABLE created in a stored procedure. If I try to use the loop as usual, the compiler complains that the table does not exist. This makes sense because the compiler does not recognize the table because it is created dynamically. Here is an example:

    create or replace PROCEDURE maketemptab IS
    sql_stmt VARCHAR2 (500);
    OutputString VARCHAR2 (50);

    BEGIN
    -create temporary table
    sql_stmt: = ' CREATE of TABLE TEMPORARY GLOBAL globtemptab (id NUMBER, col1 VARCHAR2 (50))';
    EXECUTE IMMEDIATE sql_stmt;
    dbms_output.put_line ('... created table ');

    -Insert a row into the temporary table
    sql_stmt: = "INSERT INTO globtemptab values (1, 'some data of a test')';"
    EXECUTE IMMEDIATE sql_stmt;
    dbms_output.put_line ('... inserted row ');

    -Insert a row into the temporary table
    sql_stmt: = ' INSERT INTO globtemptab values (2, "some more test data");
    EXECUTE IMMEDIATE sql_stmt;
    dbms_output.put_line ('... inserted row ');

    -Select the row on temporary table
    sql_stmt: = 'SELECT col1 FROM globtemptab WHERE id = 1';
    EXECUTE IMMEDIATE sql_stmt INTO outputstring;
    dbms_output.put_line ('... selected line: ' | outputstring);

    -drop temporary table
    sql_stmt: = 'DROP TABLE globtemptab;
    EXECUTE IMMEDIATE sql_stmt;
    dbms_output.put_line ('... moved table ');

    -display the result set
    for tabdata loop (select col1 from globtemptab)
    dbms_output.put_line ('... test of recovered data are' | tabdata.col1)
    end loop;
    end;


    In short, how to rewrite the SQL below the comment "to display the result set" using the dynamic sql?

    Thank you
    Amedeo.

    Hello

    Try this:

    CREATE OR REPLACE PROCEDURE maketemptab IS
       sql_stmt     VARCHAR2(500);
       outputstring VARCHAR2(50);
       v_cursor     SYS_REFCURSOR;
       v_col1       VARCHAR2(30);
    BEGIN
       -- create temp table
       sql_stmt := 'CREATE GLOBAL TEMPORARY TABLE globtemptab(id NUMBER, col1 VARCHAR2(50))';
       EXECUTE IMMEDIATE sql_stmt;
       dbms_output.put_line('...table created');
    
       -- insert row into temp table
       sql_stmt := 'INSERT INTO globtemptab values (1, ''some test data'')';
       EXECUTE IMMEDIATE sql_stmt;
       dbms_output.put_line('...row inserted');
    
       -- insert row into temp table
       sql_stmt := 'INSERT INTO globtemptab values (2, ''some more test data'')';
       EXECUTE IMMEDIATE sql_stmt;
       dbms_output.put_line('...row inserted');
    
       -- select row from temp table
       sql_stmt := 'SELECT col1 FROM globtemptab WHERE id=1';
       EXECUTE IMMEDIATE sql_stmt
          INTO outputstring;
       dbms_output.put_line('...row selected: ' || outputstring);
    
       OPEN v_cursor FOR 'SELECT col1 FROM globtemptab';
    
       LOOP
          FETCH v_cursor
             INTO v_col1;
          EXIT WHEN v_cursor%NOTFOUND;
          dbms_output.put_line('...test data retrieved is' || v_col1);
       END LOOP;
       CLOSE v_cursor;
    
       -- drop temp table
       sql_stmt := 'DROP TABLE globtemptab';
       EXECUTE IMMEDIATE sql_stmt;
       dbms_output.put_line('...table dropped');
    END;
    /
    

    Kind regards

  • SQL query | To display the result of the particular format table

    Hello

    I need to generate the table results in the appropriate format.

    Input samples:

    with test01
    tant_que)
    Select ' 10 'field01, field02 ' 01', 'X' double union field03
    Select ' 10 'field01, field02 ' 02', 'X' double union field03
    Select ' 10 'field01, field02 ' 03', 'X' double union field03
    Select ' 20 'field01, field02 ' 01', 'X' double union field03
    Select ' 20 'field01, field02 ' 02', 'X' of the double field03
    ) select * from test01.

    FI FI F
    -- -- -
    10 01 X
    10 02 X
    10 03 X
    20 01 X
    20 02 X

    5 selected lines.

    Expected results:

    FI F F F
    -- - - -
    10 X X X
    20 X X

    2 selected lines.

    I am not able to do that. Could you help me with this?

    pivot search you will get what you want...

  • Order of execution of SQL statements

    Hello

    I have two SQL statements where the first statement executes on a table with more than 40 million lines, the second statement is running on a table more 6 million lines.  When they are running their own each take about 0.15 seconds to run, but when combined they take 20 minutes to run, (the second SQL statement is inserted in the WHERE clause of the statement of first).  It would seem that after combining these statements, the first statement goes through all 40 million lines before it performs the SELECT in the WHERE clause.  I think that what is necessary is to ensure the SELECT in the WHERE clause is executed first... or something like that!  Anyone has any ideas on how to combine these statements but not suffer from the performance impact?

    The first statement is:

    Select csi.instance_id,

    OEL.ordered_item

    of apps.csi_item_instances csi,.

    Apps.oe_order_lines_all oel

    where csi.instance_id in

    (1718000,3698000,48740202)

    and csi.last_oe_order_line_id = oel.line_id;

    The second statement is:

    Select / * + INDEX (IEA (attribute_id)) * /.

    IEA.instance_id

    apps.csi_iea_values do

    where iea.attribute_id = 10004

    and iea.attribute_value is not null;

    The joint return is:

    Select csi.instance_id,

    OEL.ordered_item

    of apps.csi_item_instances csi,.

    Apps.oe_order_lines_all oel

    where csi.instance_id in

    (select / * + INDEX (IEA (attribute_id)) * /)

    IEA.instance_id

    apps.csi_iea_values do

    where iea.attribute_id = 10004

    and iea.attribute_value is not null)

    and csi.last_oe_order_line_id = oel.line_id;

    Thanks for any help,

    Mike

    Your subquery returns probably just two values that you did originally as constants - but the optimizer thinks that you're going to get 564 K lines.  This is why the indicator for the simple query has a beneficial effect, it forces the Oracle to use an index when it would otherwise make a search.

    When the subquery is incorporated, however, the optimizer uses its cardinality expected to decide whether to use a nested loop join or the hash join to CSI_ITEM_INSTANCES, since the large enough estimate, he uses the hash with a join analysis complete.  That's why I pointed out that the fact to tell the optimizer to how many lines outside the subquery should make a difference.

    Have you tried the "common table expression" approach, rather than approach no_merge, but it would not help because it does not change the optimizer for cardinality estimate.  If you want to repeat the method CTE adding boards / * + materialize cardinality (2) * / to the query in the WITH clause, you should get the desired result.

    Concerning

    Jonathan Lewis

  • How to execute a SQL statement that is stored within a SQL Table

    Hello

    If someone please help me with the following problem I would be eternally grateful

    I have a SQL statement that is stored inside a certain SQL table, I want to use this SQL statement inside my PL/SQL procedure.

    Thought a simple solution was to get the SQL statement in a table, and then run it, but how could I do so exactly with PL/SQL? I only started to play with PL/SQL in the last days.

    Thanks in advance!

    This is what it looks like more or less:

    Display result for:

    ---------------------

    SELECT TRIM (OBJ_VALU_TXT)

    OF OBJ_VALU_DOC

    WHERE TYPE_OBJET = 'FLD '.

    AND OBJECT_CODE = 15443

    AND OBJ_VALU_CD = 'CAB '.

    ORDER BYDOC_SEQ_NO

    00001

    ------------------------------------------------------------------

    SELECT

    VALUE (MAX (RECEIPT_NO) + 1,: OUT-COMP-FACTOR)

    THE FRONT DESK

    WHERE (RECEIPT_NO BETWEEN

    (: OUT-COMP-FACTOR AND: OUT TO A NUMBER) OR

    (RECEIPT_NO >: OUT-COMP-FACTOR AND)

    (: OUT-TO-NUMBER = 0)

    Here's a demo of your condition.

    create table t (col1 varchar2 (200));

    table created

    insert into values t ('select * from double ');

    1 row inserted

    declare
    v_col varchar2 (200);
    v_val varchar2 (200);
    Start

    Select col1 in t v_col;

    run immediately v_col in v_val;
    dbms_output.put_line (v_val);
    end;

    -----
    X

    Use in the clause, you can use as many variables as needed. But the basic approach remains the same.

    But storage in DB SQL is not an efficient design.

    Ishan

  • I'm getting "ORA-00900: invalid SQL statement" error. ?

    I installed oracle 11 GR 2. and 'DBMS_METADATA_DIFF.COMPARE_ALTER ('TABLE', 'TBL_A', 'TBL_A','USER1 ','USER2 ')"to see the result as below, but I'm" ORA-00900: invalid SQL statement "error.   Any idea?



    I use:


    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production

    PL/SQL Release 11.2.0.1.0 - Production

    CORE 11.2.0.1.0 Production

    AMT for 32-bit Windows: Version 11.2.0.1.0 - Production

    NLSRTL Version 11.2.0.1.0 - Production




    SQL > desc user1.tbl_a
    Name                                      Null?    Type
    ----------------------------------------- -------- ----------------------------
    FIELD_A1 NOT NULL NUMBER
    FIELD_A2 VARCHAR2 (20)
    FIELD_A4 NOT NULL NUMBER (5.2)
    FIELD_A5 VARCHAR2 (10)
    FIELD_A6 NOT NULL NUMBER (2)

    SQL > desc user2.tbl_a
    Name                                      Null?    Type
    ----------------------------------------- -------- ----------------------------
    FIELD_A1 NOT NULL NUMBER
    FIELD_A2 VARCHAR2 (50)
    FIELD_A3                                           DATE
    FIELD_A4 NUMBER (5.2)
    FIELD_A5 NOT NULL VARCHAR2 (10)




    SQL > select dbms_metadata_diff.compare_alter ('TABLE', 'TBL_A', 'TBL_A', 'USER1', 'USER2') of double

    expected result:

    DBMS_METADATA_DIFF.COMPARE_ALTER ('TABLE', 'TBL_A', 'TBL_A', 'U1', 'U2')
    --------------------------------------------------------------------------------
    ALTER TABLE 'U1 '. "" ADD TBL_A "(DATE OF THE"FIELD_A3")
    ALTER TABLE 'U1 '. "" TBL_A "DROP ("FIELD_A6")
    ALTER TABLE 'U1 '. "" CHANGE TBL_A ' ("FIELD_A2' VARCHAR2 (50))
    ALTER TABLE 'U1 '. "" TBL_A ' CHANGE ("FIELD_A4" NUMBER (5.2) DEFAULT 0)
    ALTER TABLE 'U1 '. "" CHANGE TBL_A ' ('FIELD_A4' NULL)
    ALTER TABLE 'U1 '. "" CHANGE TBL_A ' ('FIELD_A5' ACTIVATE NOT NULL)

    Thanks for the reply rp,

    I got the result using "select dbms_metadata_diff.compare_alter ('TABLE', 'TBL_A', 'TBL_A', 'USER1', 'USER2') from dual"

  • How to 'show' a static pseudo index using SQL statement select?

    Hello again,

    I have to post a time of 24 hours as an index. (00:00 - 23:00)
    It's easy, if data are available.

    But, if the data are not regularly exist on specific time (the time is not regular, IE: 00:00, 01:00, 05:00, 08:00, 10:00, 11:00, 23:00), then it of OK for a TABLE, but not for a CHART.

    Here is the story:

    I've written a SQL statement that can 'choose' what to display respectively the time available. The result will appear on the map: days or the time is used for the x-axis and the respective value on axis y.
    Example:
    + If the data consists of 'days' (ie: the last 5 days from now on, 16/07/2012, 17/07/2012, 18/07/2012, 19/07/2012, 20/07/2012), the chart will display these dates on the x-axis.
    + If the data consists of 'hours' (ie: only 1 day, hour 00:00 - 23:00), then the chart shows the hours on the x-axis.

    If the 'hours' are not regular, means: there is no data on the specific hours, the result of the query is not as regular, average: the value of X - axis "jumps" irregularly.

    Question:
    Is it possible to interrogate our own static value?
    for example:
    Select 'Hello' from dual-> result: 'Hello', 1 column, 1 line
    But how to display it into several lines, i.e.:

    Time
    *****
    0
    1
    2
    3
    4
    5
    ...
    ...
    23


    Note:
    the x-axis on the graph model can be customized only for 1 single mode, example: 'Days',
    but of course it will not appear correctly if the result of the query are "hours."
    This means: I have to find the workaround on the SQL query.


    DB: ORA 11


    Thank you and best regards.

    You can generate mulltiple rows if you use LEVEL and CONNECT BY:

    SQL> select level
      2  from   dual
      3  connect by level <= 10;
    
         LEVEL
    ----------
             1
             2
             3
             4
             5
             6
             7
             8
             9
            10
    
    10 rows selected.
    
    SQL>  select sysdate+level-1
      2  from   dual
      3   connect by level <= 10;
    
    SYSDATE+LEVEL-1
    -------------------
    20-07-2012 12:48:26
    21-07-2012 12:48:26
    22-07-2012 12:48:26
    23-07-2012 12:48:26
    24-07-2012 12:48:26
    25-07-2012 12:48:26
    26-07-2012 12:48:26
    27-07-2012 12:48:26
    28-07-2012 12:48:26
    29-07-2012 12:48:26
    
    10 rows selected.
    
    SQL> select to_char(trunc(sysdate), 'hh24')+level-1
      2  from  dual
      3  connect by level <= 24;
    
    TO_CHAR(TRUNC(SYSDATE),'HH24')+LEVEL-1
    --------------------------------------
                                         0
                                         1
                                         2
                                         3
                                         4
                                         5
                                         6
                                         7
                                         8
                                         9
                                        10
                                        11
                                        12
                                        13
                                        14
                                        15
                                        16
                                        17
                                        18
                                        19
                                        20
                                        21
                                        22
                                        23
    
    24 rows selected.
    
  • "Balance forward" SQL statement

    Anyone developing a SQL statement which helps to carry forward balances? A UNION query might work?

    Here is my example where I need to join the 3 tables and display the results. According to data from the example below, I am looking for an application that allows me to illustrate that instances of Acrobat 9 software installed using 6 license capacity, or a balance of 4 which can be applied to Instances of installed software Acrobat 8.

    Table: LICENSE

    LICENSENUM SWLICENSE LICENSECAPACITY
    '1001' "adobe Acrobat 9' 10'

    Table: LICENSESW

    PRIORITY SWPRODUCT LICENSENUM
    "1001'"acrobat 9' 1".
    "1001'"acrobat 8' 2".

    Table: INSTALLEDSW

    INSTALLEDSW
    'Acrobat 9'
    'Acrobat 9'
    'Acrobat 9'
    'Acrobat 9'
    'Acrobat 9'
    'Acrobat 9'
    'Acrobat 8'
    'Acrobat 8'
    'Acrobat 8'
    'Acrobat 8'
    'Acrobat 8'


    I can write a select for total of charges, but this does not allow me to carry a balance forward to be applied on Acrobat 8 (priority 2).

    Select a LICENSE. SWLICENSE, LICENSE. LICENSECAPACITY County (INSTALLEDSW. INSTALLEDSW) as INSTALLED_COUNT
    license, LICENSESW, INSTALLEDSW
    where the LICENSE. LICENSENUM = LICENSESW. LICENSENUM
    AND LICENSESW. SWPRODUCT = INSTALLEDSW. INSTALLEDSW
    LICENSE group. SWLICENSE, LICENSE. LICENSECAPACITY;

    Results:
    SWLICENSE LICENSECAPACITY INSTALLED_COUNT
    "Adobe Acrobat 9' 11 ' 10' '.



    I need the results that look like this, where the balance of 4 is postponed after the first line:

    SWLICENSE LICENSECAPACITY INSTALLED_PRODUCT INSTALLED_COUNT
    "' Adobe Acrobat 9 6" "' Acrobat 6' 9" ""
    «' Adobe Acrobat 4' 9 "' Acrobat 8 5'"»

    Not easy to follow your example data, but if I show which, in my opinion, you are trying to achieve using the emp table, you can see if it helps...

    SQL> select deptno, empno, ename
      2        ,count(*) over (partition by deptno) as dept_count
      3        ,count(*) over (partition by deptno) - row_number() over (partition by deptno order by empno) as remaining
      4  from   emp
      5  order by deptno, empno;
    
        DEPTNO      EMPNO ENAME      DEPT_COUNT  REMAINING
    ---------- ---------- ---------- ---------- ----------
            10       7782 CLARK               3          2
            10       7839 KING                3          1
            10       7934 MILLER              3          0
            20       7369 SMITH               5          4
            20       7566 JONES               5          3
            20       7788 SCOTT               5          2
            20       7876 ADAMS               5          1
            20       7902 FORD                5          0
            30       7499 ALLEN               6          5
            30       7521 WARD                6          4
            30       7654 MARTIN              6          3
            30       7698 BLAKE               6          2
            30       7844 TURNER              6          1
            30       7900 JAMES               6          0
    
    14 rows selected.
    

    by using the count() and row_number() analytical functions (you can use others such as sum(), avg(), lag(), lead(), etc. as needed), you can make treatment that carries forward, backward or "groups" (aka partitions) data.

Maybe you are looking for