RETURN TO THE UPDATE QUERY CLAUSE

I have a request written in Postgres.   This will pick up the records in the table job_information with the State, as provided by the application (ex: "READY_TO_RUN") and with limit of records like the one provided by the application (ex: 100), then updates the job_information with app get (ex: "ACHIEVEMENTS") and returns that defined (means, returns the data table job_information total for these got put to date with the given State) records for the use of the application.

Can someone give me advice on the translation in Oracle?   Thank you!!

Query in Postgres

UPDATE job_information AS J1
SET status=?
FROM
  (SELECT job_name,
    job_group,
    created_date
  FROM job_information
  WHERE status           =?
  AND CURRENT_TIMESTAMP >= scheduled_execution_time
  ORDER BY scheduled_execution_time limit ?
  ) AS J2
WHERE J1.job_name   = J2.job_name
AND J1.job_group    = J2.job_group
AND J1.created_date = J2.created_date RETURNING *;

Example of a query (in postgres):

UPDATE job_information AS J1
SET status= 'ACQUIRED'
FROM
  (SELECT job_name,
    job_group,
    created_date
  FROM job_information
  WHERE status           = 'READY_TO_RUN'
  AND CURRENT_TIMESTAMP >= scheduled_execution_time
  ORDER BY scheduled_execution_time limit 100
  ) AS J2
WHERE J1.job_name   = J2.job_name
AND J1.job_group    = J2.job_group
AND J1.created_date = J2.created_date RETURNING *;

Oracle SQL - query, I wrote it is not working

UPDATE JOB_INFORMATION SET STATUS=
(
WITH J2 as (
                        select job_name, job_group, created_date from (SELECT job_name, job_group, created_date FROM job_information WHERE status= :b and current_timestamp >= scheduled_execution_time order by scheduled_execution_time ) where rownum<= :c
            )
SELECT distinct :a FROM JOB_INFORMATION J1, J2 WHERE J1.job_name = J2.job_name AND J1.job_group = J2.job_group AND J1.created_date = J2.created_date
)
RETURNING * FROM JOB_INFORMATION BULK COLLECT INTO SOMETHING ;
  1. create or replace package test_pack
  2. as
  3. type r_tab is (record
  4. test.job_name%type job_name,
  5. (status test.status%type);
  6. type t_tab is table of the r_tab;
  7. function test_func (v_status_o VARCHAR, v_status_i VARCHAR) - USE VARCHAR2
  8. T_tab RETURN PIPELINED;
  9. end;
  10. /
  11. create or replace the BODY of PACKAGE as test_pack
  12. function test_func (v_status_o VARCHAR2, v_status_i VARCHAR2) return t_tab pipelined as
  13. PRAGMA AUTONOMOUS_TRANSACTION;
  14. v_tab t_tab;
  15. Start
  16. Update test
  17. set status = v_status_o :-
  18. where Job_name in (select job_name TEST where status = :v_status_i).
  19. job_name, return STATUS
  20. bulk collect into v_tab;
  21. commit;
  22. because me in 1... loop v_tab. Count
  23. pipe row (v_tab (i));
  24. end loop;
  25. end;
  26. end;
  27. /

REMOVE the colon before parameters and use the same types of data

Tags: Database

Similar Questions

  • Return in the MERGE statement clause

    Hello

    I use Oracle 10 g Version

    I tried the code using UPDATE with return Clause & MERGER with return below Clause.

    I have not found ANY error while working with the UPDATE statement. Here is the code with the UPDATE statement

    DECLARE
       TYPE empno_list IS TABLE OF emp.empno%TYPE;
       vempno_list   empno_list;
    BEGIN
          UPDATE emp
             SET comm = 11
           WHERE deptno IN (SELECT deptno FROM dept)
       RETURNING empno
            BULK COLLECT INTO vempno_list;
       FOR i IN vempno_list.FIRST .. vempno_list.LAST
       LOOP
          DBMS_OUTPUT.put_line ('Values of EMP ' || vempno_list (i));
       END LOOP;
    END;   
    

    But PL/SQL error: ORA-00933: SQL not correctly completed command when you work with the MERGE statement

    declare 
     type empno_list  is  table of emp.empno%type;
     vempno_list empno_list;
    begin                
       merge into emp tgt 
          using dept src
            on (src.deptno =tgt.deptno)
            when matched then 
             update set tgt.comm=12
           returning tgt.empno bulk collect into vempno_list ;
           
            for i in vempno_list.first .. vempno_list.last loop
                    dbms_output.put_line('Values of EMP '||vempno_list(i) ) ;
            end loop;
    end;  
    

    Please suggest me

    Probably because BACK IN clause does not belong to the MERGE statement. It is available only for INSERT, UPDATE, and DELETE. Here's the quote from Oracle Documentation:

    The static method RETURNING INTO article belongs to a DELETE , INSERT , or UPDATE statement. The dynamic RETURNING INTO article belongs to a EXECUTE IMMEDIATE statement.

    And here is the link.

    Back IN the Clause

    It will be useful.

    Ishan

  • return the empty record only when no results not returned by the main query

    It is a question of SQL (not PL/SQL)...

    Let's say I have the following text:

    Full_name SELECT NULL, NULL, NULL last_update_date address
    OF the double
    UNION ALL
    SELECT full_name, address, last_update_date
    Employees
    WHEN TRUNC (sysdate) = TRUNC (last_update_date)

    If the second part of the query retrieves no rows, it works beautifully and I get a blank line; However, if the second part of the query returns records, I get a blank line over my dataset I want.

    How can I create a SQL statement that executes only the first query (before the union all) when no result is returned from the second. Also, I don't want to exceute the query twice only if I can get a count of the records because my actual query is much more complex than the example I've provided here.

    Thanks in advance!
    Emily

    Hello

    You can try to use a subquery factoring (WITH clause)
    The query is executed only once, the query results are cached in memory or in a temporary table.
    and you can view these results several times in the main query:

    WITH second_query AS (
      -- your second query here
      SELECT full_name, address, last_update_date
      FROM employees
      WHERE TRUNC(sysdate)=TRUNC(last_update_date)
    )
    SELECT full_name, address, last_update_date
    FROM second_query
    UNION ALL
    SELECT NULL full_name, NULL address, NULL last_update_date
    FROM dual
    WHERE NOT EXISTS ( SELECT 1 FROM second_query)
    

    Published by: kordirko on 2010-07-08 02:02

  • Not the rows returned by the spatial query wrapped in SELECT * FROM...

    Hello

    When you run a query with SDO_EQUAL sub, I get a very strange behavior. The SDO_EQUAL query on its own works very well, but if I wrap in SELECT * from there, I get no results. If I wrap SDO_ANYINTERACT in SELECT * from there, I get the expected result.

    It seems like the spatial index is used during the execution of the ordinary, but not when SDO_EQUAL request wrapped in SELECT * FROM. Weird. The spatial index is also not used when SDO_ANYINTERACT is wrapped in SELECT * FROM... so I don't know why that returns the correct answer.

    I get this problem on 11.2.0.2 on Red Hat Linux 64-bit and 11.2.0.1 on Windows XP 32-bit (i.e., all versions of 11g I've tried). The query works as expected on 10.2.0.5 on Windows Server 2003 64-bit.

    Any ideas?

    Confused in Dublin (John)

    Test case...
    SQL> 
    SQL> -- Create a table and insert the same geometry twice
    SQL> DROP TABLE sdo_equal_query_test;
    
    Table dropped.
    
    SQL> CREATE TABLE sdo_equal_query_test (
      2  id NUMBER,
      3  geometry SDO_GEOMETRY);
    
    Table created.
    
    SQL> 
    SQL> INSERT INTO sdo_equal_query_test VALUES (1,
      2  SDO_GEOMETRY(3003, 81989, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1),
      3  SDO_ORDINATE_ARRAY(1057.39, 1048.23, 4, 1057.53, 1046.04, 4, 1057.67, 1043.94, 4, 1061.17, 1044.60, 5, 1060.95, 1046.49, 5, 1060.81, 1047.78, 5, 1057.39, 1048.23, 4)));
    
    1 row created.
    
    SQL> 
    SQL> INSERT INTO sdo_equal_query_test VALUES (2,
      2  SDO_GEOMETRY(3003, 81989, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1),
      3  SDO_ORDINATE_ARRAY(1057.39, 1048.23, 4, 1057.53, 1046.04, 4, 1057.67, 1043.94, 4, 1061.17, 1044.60, 5, 1060.95, 1046.49, 5, 1060.81, 1047.78, 5, 1057.39, 1048.23, 4)));
    
    1 row created.
    
    SQL> 
    SQL> -- Setup metadata
    SQL> DELETE FROM user_sdo_geom_metadata WHERE table_name = 'SDO_EQUAL_QUERY_TEST';
    
    1 row deleted.
    
    SQL> INSERT INTO user_sdo_geom_metadata VALUES ('SDO_EQUAL_QUERY_TEST','GEOMETRY',
      2  SDO_DIM_ARRAY(SDO_DIM_ELEMENT('X', 0, 100000, .0001), SDO_DIM_ELEMENT('Y', 0, 100000, .0001), SDO_DIM_ELEMENT('Z', -100, 4000, .0001))
      3  ,81989);
    
    1 row created.
    
    SQL> 
    SQL> -- Create spatial index
    SQL> DROP INDEX sdo_equal_query_test_spind;
    DROP INDEX sdo_equal_query_test_spind
               *
    ERROR at line 1:
    ORA-01418: specified index does not exist
    
    
    SQL> CREATE INDEX sdo_equal_query_test_spind ON sdo_equal_query_test(geometry) INDEXTYPE IS MDSYS.SPATIAL_INDEX;
    
    Index created.
    
    SQL> 
    SQL> -- Ensure data is valid
    SQL> SELECT sdo_geom.validate_geometry_with_context(sdo_cs.make_2d(geometry), 0.0001) is_valid
      2  FROM sdo_equal_query_test;
    
    IS_VALID
    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    TRUE
    TRUE
    
    2 rows selected.
    
    SQL> 
    SQL> -- Check query results using sdo_equal
    SQL> SELECT b.id
      2  FROM sdo_equal_query_test a, sdo_equal_query_test b
      3  WHERE a.id = 1
      4  AND b.id != a.id
      5  AND sdo_equal(a.geometry, b.geometry) = 'TRUE';
    
            ID
    ----------
             2
    
    1 row selected.
    
    SQL> 
    SQL> -- Check query results using sdo_equal wrapped in SELECT * FROM
    SQL> -- Results should be the same as above, but... no rows selected
    SQL> SELECT * FROM (
      2       SELECT b.id
      3       FROM sdo_equal_query_test a, sdo_equal_query_test b
      4       WHERE a.id = 1
      5       AND b.id != a.id
      6       AND sdo_equal(a.geometry, b.geometry) = 'TRUE'
      7  );
    
    no rows selected
    
    SQL> 
    SQL> -- So that didn't work.  Now try sdo_anyinteract... this works ok
    SQL> SELECT * FROM (
      2       SELECT b.id
      3       FROM sdo_equal_query_test a, sdo_equal_query_test b
      4       WHERE a.id = 1
      5       AND b.id != a.id
      6       AND sdo_anyinteract(a.geometry, b.geometry) = 'TRUE'
      7  );
    
            ID
    ----------
             2
    
    1 row selected.
    
    SQL> 
    SQL> -- Now try a scalar query
    SQL> SELECT * FROM (
      2       SELECT b.id
      3       FROM sdo_equal_query_test a, sdo_equal_query_test b
      4       WHERE a.id = 1
      5       AND b.id != a.id
      6  );
    
            ID
    ----------
             2
    
    1 row selected.
    
    SQL> spool off
    Here is the plan of the explain output for the query that works. Note that the spatial index is used.
    SQL> EXPLAIN PLAN FOR
      2  SELECT b.id
      3  FROM sdo_equal_query_test a, sdo_equal_query_test b
      4  WHERE a.id = 1
      5  AND b.id != a.id
      6  AND sdo_equal(a.geometry, b.geometry) = 'TRUE';
    
    Explained.
    
    SQL> @?/rdbms/admin/utlxpls.sql
    
    PLAN_TABLE_OUTPUT
    ------------------------------------------------------------------------------------------------------------
    Plan hash value: 3529470109
    
    ------------------------------------------------------------------------------------------------------------
    | Id  | Operation                     | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
    ------------------------------------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT              |                            |     1 |  7684 |     3   (0)| 00:00:01 |
    |   1 |  RESULT CACHE                 | f5p63r46pbzty4sr45td1uv5g8 |       |       |            |       |
    |   2 |   NESTED LOOPS                |                            |     1 |  7684 |     3   (0)| 00:00:01 |
    |*  3 |    TABLE ACCESS FULL          | SDO_EQUAL_QUERY_TEST       |     1 |  3836 |     3   (0)| 00:00:01 |
    |*  4 |    TABLE ACCESS BY INDEX ROWID| SDO_EQUAL_QUERY_TEST       |     1 |  3848 |     3   (0)| 00:00:01 |
    |*  5 |     DOMAIN INDEX              | SDO_EQUAL_QUERY_TEST_SPIND |       |       |     0   (0)| 00:00:01 |
    ------------------------------------------------------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       3 - filter("B"."ID"!=1)
       4 - filter("A"."ID"=1 AND "B"."ID"!="A"."ID")
       5 - access("MDSYS"."SDO_EQUAL"("A"."GEOMETRY","B"."GEOMETRY")='TRUE')
    ..... other stuff .....     
    Here is the plan of the explain output for the query is not working. Note that the spatial index is not used.
    SQL> EXPLAIN PLAN FOR
      2  SELECT * FROM (
      3     SELECT b.id
      4     FROM sdo_equal_query_test a, sdo_equal_query_test b
      5     WHERE a.id = 1
      6     AND b.id != a.id
      7     AND sdo_equal(a.geometry, b.geometry) = 'TRUE'
      8  );
    
    Explained.
    
    SQL> @?/rdbms/admin/utlxpls.sql
    
    PLAN_TABLE_OUTPUT
    --------------------------------------------------------------------------------------------------
    Plan hash value: 1024466006
    
    --------------------------------------------------------------------------------------------------
    | Id  | Operation           | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
    --------------------------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT    |                            |     1 |  7684 |     6   (0)| 00:00:01 |
    |   1 |  RESULT CACHE       | 2sd35wrcw3jr411bcg3sz161f6 |       |       |            |          |
    |   2 |   NESTED LOOPS      |                            |     1 |  7684 |     6   (0)| 00:00:01 |
    |*  3 |    TABLE ACCESS FULL| SDO_EQUAL_QUERY_TEST       |     1 |  3836 |     3   (0)| 00:00:01 |
    |*  4 |    TABLE ACCESS FULL| SDO_EQUAL_QUERY_TEST       |     1 |  3848 |     3   (0)| 00:00:01 |
    --------------------------------------------------------------------------------------------------
    
    Predicate Information (identified by operation id):
    ---------------------------------------------------
    
       3 - filter("B"."ID"!=1)
       4 - filter("A"."ID"=1 AND "B"."ID"!="A"."ID" AND
                  "MDSYS"."SDO_EQUAL"("A"."GEOMETRY","B"."GEOMETRY")='TRUE')
    ..... other stuff .....               

    Yes, this is the bug 9740355. You can get a 11.2.0.1 patch, or wait for 11.2.0.3.

  • The UPDATE query help

    I'm on 10G.

    Something is weird. Each customer_id to table X is from the subquery. Basically by train to fill the column of SUSPICION in X to a value of H when there are name/store is from the subquery using the customer_id.

    When I run just the subquery returns 287 matches (and all these 287 X is), but when I try to UPDATE X only update the 260 H lines, but should 287? 27 never update, why? The customer_id are distinct or not NULL values.

    What I am doing wrong?

    Like I said I have selected everything from (subquery), I pasted in Excel. I chose all the customer_ids of X and when I do a VLOOKUP, everything matches, but the query updates only 260 and 287 not? :- )


    UPDATE PROSPECTS_FEB_TEST X
    SET X.HINT = 'H' WHERE X.customer_id IN

    (SELECT a.customer_id
    PROSPECTS OF A, B CONNECTED
    WHERE B.LAST_NAME = A.NAME_LAST
    AND B.FIRST_NAME = A.NAME_FIRST
    AND B.STORE = A.STORE);

    What you get from this?

    SELECT COUNT(DISTINCT a.customer_id)
    FROM prospects a, connected b
    WHERE b.last_name = a.name_last and
          b.first_name = a.name_first and
          b.store = a.store
    

    Is customer_id a numeric field or a varchar2? If it's a varchar2, could their space having in one of the other tables?

    John

  • Error returned during the update of the Organization of the user

    Hello

    I'm on OIM 11 GR 2 PS1 and tried to update the user organization.

    The user update code looks like this:

    String new_act_key = "";

    User user = null;

    Result UserManagerResult = null; OIMClient API

    HashMap < String, Object > attributeMap =.

    new HashMap < String, Object > ();

    attributeMap.put ("User Login", usr_login);

    attributeMap.put ("Email", usr_email);

    attributeMap.put ("phone number", phone);

    attributeMap.put ("employee ID", empNo);

    attributeMap.put ("title", title);

    attributeMap.put ("act_key", new_act_key);

    User = new User (usr_login, attributeMap);

    new_act_key = getOrganizationID (orgCode);

    result = userManager.modify ("user login", usr_login, user);

    Logger.Warning ("DEBUG CDE: userlogin is now changed");

    private String getOrganizationID (String orgCode) {}
    OrganizationManager = orgManager
    Platform.getService (OrganizationManager.class);
    Organization org;
    try {}

    org = orgManager.getDetails ("OrganizationCode", orgCode, null);
    Return org.getEntityId ();

    } catch (OrganizationManagerException e) {}
    System.out.println ("ERROR de CRC: Exception encountered in CDE CreateUsersST, getOrganizationID for orgCode:" +)
    orgCode);
    e.printStackTrace ();
    Returns a null value.
    } catch (SearchKeyNotUniqueException e) {}
    System.out.println ("ERROR de CRC: Exception encountered in CDE CreateUsersST, getOrganizationID for orgCode:" +)
    orgCode);
    e.printStackTrace ();
    Returns a null value.
    }
    }

    The error is:

    [2014 07-22 T 18: 01:31.761 - 06:00] [WLS_OIM1] [ERROR] [] [oracle.iam.request.impl] [tid: OIMQuartzScheduler_Worker-8] [username: oiminternal] [ecid: 0000KTN9qNmFg400jzwkno1Jn9Kz000003, 1:24388] [APP: IOM #11.1.2.0.0] Validation failed with the error message java.lang.ClassCastException: java.lang.String can not be cast as java.lang.Long

    Can we use the java code for updating the Organization of the user?

    How can I fix this code?

    Thank you

    Khanh

    From the top of my head act_key must be put in the map as Long

  • make a function using the update query - error PLS-00103

    I get the following error message in my pl/sql developer every time, I try to create this function in my package
    PLS3-00103 encountered the symbol ";" when expecting one of the following return

    Please note, I'm trying to do is to get a user entered to perform an update for a specific row in a table called accountingtable that is located in the CDC schema. I don't want to make a comeback but in my update function.



    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    The package Specfication
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    FUNCTION update_price (needed_newprice in ccl.accountingtable.price%rowtype,
    partforupdate in ccl.accountingtable.part_id%rowtype,
    colourpart to ccl.accountingtable.colour_id%rowtype);

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    package body
    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    FUNCTION update_price (needed_newprice in ccl.accountingtable.price%rowtype
    partforupdate in ccl.accountingtable.part_id%rowtype,
    colourpart to ccl.accountingtable.colour_id%rowtype);



    BEGIN
    Update accountingtable
    fixed price = (needed_newprice)
    where part_id = (partforupdate)
    and colour_id = (colourpart);

    END update_price;

    Thanks in advance for any help.

    Procedure update_price (needed_newprice in ccl.accountingtable.price%rowtype,
    partforupdate in ccl.accountingtable.part_id%rowtype,
    colourpart to ccl.accountingtable.colour_id%rowtype);

    No % rowtype. Use type %

    Procedure update_price (needed_newprice in ccl.accountingtable.price%type,
    partforupdate in ccl.accountingtable.part_id%type,
    colourpart to ccl.accountingtable.colour_id%type);

    is not respected in the body

    create or replace pacakage body test_board is

    procedure update_price (needed_newprice in ccl.accountingtable.price%rowtype---ici
    partforupdate in ccl.accountingtable.part_id%rowtype,
    colourpart to ccl.accountingtable.colour_id%rowtype) is

    Published by: user2679851 on June 2, 2010 14:01

  • using the update query exists

    Hello
    I run the query below
    and I'm ggetting error

    update of sh_mem one
    Set a.custno =

    (select b.custno in the ac_details b where to_number (a.memrefno) = b.memberno)
    where exists (select 1 from ac_details b where to_number (a.memrefno) = b.memberno)
    SQL > /.
    Set a.custno =
    *
    ERROR on line 2:
    ORA-01407: cannot update
    ("TRIAL". "" "" sh_mem '. "" CUSTNO') with the NULL value

    number of records in both tables do not match

    Help, please

    HEMU wrote:
    OK Sir
    It worked

    But you don't score one of the posts as 'Correct' or 'useful '.

    :-(

  • Building of transport returns using the report query

    I use report Querys and report layouts. I am trying to build in some carriage returns that will recognize in my rtf model. I tried to use "Chr (10)", br, etc, but it does not work. It prints the characters instead of the carriage return. Am something Imissing?

    < COMMENTS01 > MATHEMATICS (GEL, J): rarely hands duties in time rarely comes to the class at the time. Reasons for retention Possible William works well on chr (10) MEDIA (HATTER, M): doing well on tests shows a willingness to learn chr (10) READING (ANDERSON, L): doing well on tests done well on quizzes here are the notes for their ease, these are notes of understanding. Chr (10) SCIENCE (RESOURCES, M): Basic Code 1 has trouble with Jupiter. Chr (10) < / COMMENTS01 >

    Bob,

    The literal string "Chr (10)" won't help you much.

    select 'mystring'||'chr(10)'||'mystring' from dual; -- returns 'mystringchr(10)mystring'
    select 'mystring'|| chr(10) ||'mystring' from dual; -- returns 'mystring
    mystring'
    

    See you soon,.
    Janet Tyson

  • Question about the rollback segment when you perform the update

    Undo segment is to keep data ACI (not D). I read that it taken from the book of certification, when the update is running, all the other session will be redirected to cancel the segment to get the original version of the data. Is the rollback segment just a copy of the original version of the data? Or it's the query to return data to the original version?

    For example, the original data are:

    ID name address
    1KevinToronto

    Then I run the update query:

    update user name = 'Tom' where id = 1;

    What is in the segment of cancellation then?

    There ' 1, Kevin, Toronto'.

    or

    "update users set name = 'Kevin' where id = 1"?

    Thank you

    Kevin

    da5515c1-7630-4449-8c7c-e27665cec5c6 wrote:

    Undo segment is to keep data ACI (not D). I read that it taken from the book of certification, when the update is running, all the other session will be redirected to cancel the segment to get the original version of the data. Is the rollback segment just a copy of the original version of the data? Or it's the query to return data to the original version?

    For example, the original data are:

    ID name address
    1 Kevin Toronto

    Then I run the update query:

    update user name = 'Tom' where id = 1;

    What is in the segment of cancellation then?

    There ' 1, Kevin, Toronto'.

    or

    "update users set name = 'Kevin' where id = 1"?

    Thank you

    Kevin

    This is another UPDATE statement that will set back to the original value NAME; which can be used to RESTORE the DML.

  • Dynamic display of columns in the pivot query

    I have a table called STUDENT_SCORE. I need to display the avarage score/month for 2 years and the monthly score until today "month.

    Then assume that it is April 2009. The report will look like

    Roll_id 2007avg 2008avg Jan09-Mar09 Feb 09
    101 80.9 70.9 89.7 90.9 56.8
    102 70.9 23.9 87.2 90.0 76.8


    I tried a bit, but can't fix the monthly score display dynamically.


    DDL/DML is as below


    create the table STUDENT_SCORE
    (number of roll_id,
    date of mth_id,
    The partition number);


    insert into STUDENT_SCORE values
    (101, to_date (January 1, 2006 ', ' dd/mm/yyyy'), 67.5);
    insert into STUDENT_SCORE values
    (101, to_date (February 1, 2006 ', ' dd/mm/yyyy'), 77.5);
    insert into STUDENT_SCORE values
    (101, to_date (March 1, 2006 ', ' dd/mm/yyyy'), 87.5).
    insert into STUDENT_SCORE values
    (101, to_date (April 1, 2006 ', ' dd/mm/yyyy'), 27.5);
    insert into STUDENT_SCORE values
    (101, to_date (May 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (June 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (July 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (August 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (September 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (October 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (November 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (December 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (January 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (February 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (March 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (April 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (May 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (June 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (July 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (August 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (September 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (October 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (November 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (December 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (1 January 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (February 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (March 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (April 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (May 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (June 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (July 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (August 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (September 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (October 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (November 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (December 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (101, to_date (January 1, 2009 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (January 1, 2006 ', ' dd/mm/yyyy'), 67.5);
    insert into STUDENT_SCORE values
    (102, to_date (February 1, 2006 ', ' dd/mm/yyyy'), 77.5);
    insert into STUDENT_SCORE values
    (102, to_date (March 1, 2006 ', ' dd/mm/yyyy'), 87.5).
    insert into STUDENT_SCORE values
    (102, to_date (April 1, 2006 ', ' dd/mm/yyyy'), 27.5);
    insert into STUDENT_SCORE values
    (102, to_date (May 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (June 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (July 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (August 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (September 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (October 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (November 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (December 1, 2006 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (January 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (February 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (March 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (April 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (May 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (June 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (July 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (August 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (September 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (October 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (November 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (December 1, 2007 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (1 January 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (February 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (March 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (April 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (May 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (June 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (July 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (August 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (September 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (October 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (November 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (December 1, 2008 ', ' dd/mm/yyyy'), 57.5);
    insert into STUDENT_SCORE values
    (102, to_date (January 1, 2009 ', ' dd/mm/yyyy'), 57.5);

    Hello

    The script below produces what you want (as far as I can tell, without your desired results).

    Student_score_smry subquery Gets the year and monthly averages of student_score.
    It is completely static: it always produces 11 monthly columns (from January to November) and the names of columns hardcoded (m01 through m11).
    For dynamic column names you need, I used SQL * COLUMN more orders.
    To get the variable number of monthly columns you need, SELECT from the main query clause uses a script under (dynamic_month.sql) to only show the correct number (which can be 0).

    The student_score_wk_smry of subquery retrieves the weekly averages of the student_score_wk.
    He, too, is completely static: it always produces 6 weekly columns with names hardcoded (w1 through w6).

    There are four preliminary motions, that write two scripts under:
    Prelimiary C1, C2 and C3 queries write orders of COLUMN for annual, monthly and weekly columns in dynamic_columns.sql
    Preliminary motion M written between 0 and 11 items in SELECT-clause in sub-script dynamic_month.sql

    The main script is:

    SET     FEEDBACK     OFF
    SET     LINESIZE     200
    SET     PAGESIZE     0
    SET     VERIFY          OFF
    
    SPOOL     dynamic_column.sql
    
    -- Preliminary query C1: Columns for last 2 years
    SELECT     'COLUMN     y'
         ||     LEVEL
         ||     '     HEADING     "'
         ||     TO_CHAR     ( ADD_MONTHS     ( &target_month
                             , 12 * (-3 + LEVEL)
                             )
                   , 'YYYY'
                   )
         ||     'avg"'
    FROM     dual
    CONNECT BY     LEVEL <= 2
    ;
    
    -- Preliminary query C2: 11 prior months in this year
    SELECT     'COLUMN     m'
         ||     TO_CHAR     (LEVEL, 'fm00')
         ||     '     HEADING     "'
         ||     TO_CHAR     ( ADD_MONTHS     ( TRUNC (&target_month, 'YYYY')
                             , LEVEL - 1
                             )
                   , 'MonYY'
                   )
         ||     '"'
    FROM     dual
    CONNECT BY     LEVEL <= 11
    ;
    
    -- Preliminary query C3: 6 weeks before target_month
    WITH     got_w_num     AS
    (
         SELECT     SUBSTR (week_desc, 1, 6)     AS mon_dd
         ,     ROW_NUMBER () OVER
                   (     ORDER BY     week_id     DESC
                   )     AS w_num
         FROM     week
         WHERE     TO_DATE (week_desc, 'Mon DD, YYYY')     < &target_month
    )
    SELECT     'COLUMN     w'
         ||     TO_CHAR (7 - w_num)
         ||     '     HEADING     "Week of '
         ||     mon_dd
         ||     '"'
    FROM     got_w_num
    WHERE     w_num     <= 6
    ORDER BY     w_num     DESC
    ;
    
    SPOOL     OFF
    
    -- Preliminary Query M: 0-11 months (in SELECT clause)
    SPOOL     dynamic_month.sql
    
    SELECT     ',     m'
         ||     TO_CHAR (LEVEL, 'fm00')
    FROM     dual
    WHERE     MONTHS_BETWEEN (&target_month, TRUNC (&target_month, 'YYYY')) >= 1
    CONNECT BY     LEVEL <= MONTHS_BETWEEN (&target_month, TRUNC (&target_month, 'YYYY'))
    ;
    
    SPOOL     OFF
    
    -- Restore SQL*Plus features suppressed earlier
    SET     FEEDBACK     ON
    SET     LINESIZE     80
    SET     PAGESIZE     50
    
    -- COLUMN Commands
    @dynamic_column.sql
    
    -- Main Query
    WITH     student_score_smry     AS
    (
         SELECT     roll_id
         ,     AVG (CASE WHEN TRUNC (mth_id, 'YYYY') = TRUNC (ADD_MONTHS (&target_month, -24), 'YYYY')     THEN score END)     AS y1
         ,     AVG (CASE WHEN TRUNC (mth_id, 'YYYY') = TRUNC (ADD_MONTHS (&target_month, -12), 'YYYY')     THEN score END)     AS y2
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') =             TRUNC (&target_month, 'YYYY')      THEN score END)     AS m01
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'),  1) THEN score END)     AS m02
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'),  2) THEN score END)     AS m03
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'),  3) THEN score END)     AS m04
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'),  4) THEN score END)     AS m05
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'),  5) THEN score END)     AS m06
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'),  6) THEN score END)     AS m07
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'),  7) THEN score END)     AS m08
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'),  8) THEN score END)     AS m09
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'),  9) THEN score END)     AS m10
         ,     AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 10) THEN score END)     AS m11
         FROM     student_score
         GROUP BY     roll_id
    )
    ,     got_w_num     AS
    (
         SELECT     week_id
         ,     ROW_NUMBER () OVER
                   (     ORDER BY     week_id     DESC
                   )     AS w_num
         FROM     week
         WHERE     TO_DATE (week_desc, 'Mon DD, YYYY')     < &target_month
    )
    ,     student_score_wk_smry     AS
    (
         SELECT     roll_id
         ,     AVG (CASE WHEN W_NUM = 6 THEN score END)     AS w1
         ,     AVG (CASE WHEN W_NUM = 5 THEN score END)     AS w2
         ,     AVG (CASE WHEN W_NUM = 4 THEN score END)     AS w3
         ,     AVG (CASE WHEN W_NUM = 3 THEN score END)     AS w4
         ,     AVG (CASE WHEN W_NUM = 2 THEN score END)     AS w5
         ,     AVG (CASE WHEN W_NUM = 1 THEN score END)     AS w6
         FROM     student_score_wk     s
         JOIN     got_w_num          w     ON     s.wk_id     = w.week_id
         WHERE     w_num     <= 6
         GROUP BY     roll_id
    )
    SELECT     NVL (ss.roll_id, ssw.roll_id)     AS roll_id
    ,     y1, y2
    @dynamic_month.sql
    ,     w1, w2, w3, w4, w5, w6
    FROM          student_score_smry     ss
    FULL OUTER JOIN     student_score_wk_smry     ssw     ON     ss.roll_id     = ssw.roll_id
    ORDER BY     roll_id
    ;
    

    Sub-script dynamic_column.sql might look like this:

    COLUMN     y1     HEADING     "2007avg"
    COLUMN     y2     HEADING     "2008avg"
    COLUMN     m01     HEADING     "Jan09"
    COLUMN     m02     HEADING     "Feb09"
    COLUMN     m03     HEADING     "Mar09"
    COLUMN     m04     HEADING     "Apr09"
    COLUMN     m05     HEADING     "May09"
    COLUMN     m06     HEADING     "Jun09"
    COLUMN     m07     HEADING     "Jul09"
    COLUMN     m08     HEADING     "Aug09"
    COLUMN     m09     HEADING     "Sep09"
    COLUMN     m10     HEADING     "Oct09"
    COLUMN     m11     HEADING     "Nov09"
    COLUMN     w1     HEADING     "Week of Dec 21"
    COLUMN     w2     HEADING     "Week of Dec 28"
    COLUMN     w3     HEADING     "Week of Jan 04"
    COLUMN     w4     HEADING     "Week of Jan 11"
    COLUMN     w5     HEADING     "Week of Jan 18"
    COLUMN     w6     HEADING     "Week of Jan 25"
    

    Other sub-script, dynamic_month.sql, might look like this:

    ,     m01
    ,     m02
    ,     m03
    
  • Export as .xls. Classic report type: SQL (body of function from PL/SQL returning the SQL) query

    Hey guys,.

    I'm using version 4.2.6 apex. The theme is 26.

    IM also using Listener Oracle APEX.

    I can print my classic report in PDF or CSV format.

    But I need to export it as a .xls extension.

    Report type: SQL (body of function from PL/SQL returning the SQL) query

    I need is like this cause my 'where' clause type is dynamic.

    Look at using this method: Tom's Blog: a non-standard export excel 2010 (.xlsx)

    I do something similar for downloads to excel in my projects...

    Thank you

    Tony Miller
    Software LuvMuffin
    Ruckersville, WILL

  • Subselect query returns "invalid identifier", but the nested query return lines

    I don't think it's a general SQL question.

    Select * from persons where person_id in)

    Select person_id with people whose name = 'Obama' - subquery

    ) and age > 18;

    When I run the subquery, I get:

    ORA-00904: "PERSON_ID": invalid identifier

    00904, 00000 - '% s: invalid identifier '.

    * Cause:

    * Action:

    Error on line: column 5: 8

    This is because the table people do not have the person_id field.

    But when I run the nested together query it returns all the lines in people with the AGE greater than 18.

    How is he succeeds when the subquery is obviously wrong?

    363f652b-263D-4418-933F-74a1d0a41b4c wrote:

    I don't think it's a general SQL question.

    Select * from persons where person_id in)

    Select person_id with people whose name = 'Obama' - subquery

    ) and age > 18;

    When I run the subquery, I get:

    ORA-00904: "PERSON_ID": invalid identifier

    00904, 00000 - '% s: invalid identifier '.

    * Cause:

    * Action:

    Error on line: column 5: 8

    This is because the table people do not have the person_id field.

    But when I run the nested together query it returns all the lines in people with the AGE greater than 18.

    How is he succeeds when the subquery is obviously wrong?

    Yes - this is a general SQL question and ask often enough.

    Correlated subqueries depend on the inner query, be able to see and access to the columns of the outer query. Normally see you referenced in the WHERE clause of the subquery and not in the SELECT clause, but the reference is valid in both places. This works because the columns of the tables in the main query are accessible in the subquery. "Person_id" is probably a column in the table 'people '.

    Which can be a cause of problems 'odd' when the column (in your case "person_id") is more of a table.

    Use an alias in the subquery in the subquery and you will find that it will not succeed.

    See these two articles AskTom where he addresses this specific issue

    http://asktom.Oracle.com/pls/Apex/f?p=100:11:0:P11_QUESTION_ID:3317493900346468494

    http://asktom.Oracle.com/pls/Apex/f?p=100:11:0:P11_QUESTION_ID:155200640564

  • Disable the generation of report when there are no returned by the query

    I would like to write a preliminary report trigger that disables reports generation when my main query in my data model will return no data. If possible, I would like to reuse the same query in the data model from the writing of a motion to double again.

    Thank you all

    Create a view for the main request. In this case, you just have to do it in the front trigger of the report:

    select count(*)
    into my_var
    from my_view
    where ...;
    
    if my_var =  0 then
       return false;
    else
       return true;
    end if;
    

    In where clause you can use the same settings as in your main report query.

  • sql Update query after matching with the string

    I am trying to reach the query that updates a table column with the value of the other table, after that he finds an exact match.

    So here's the table data and sample to create.
    create table code1 
    (
        codeid number,
        codedesc varchar2(60)
    );
    
    Insert into code1 values ( 1,'R1 CONTRACTS');
    
    Insert into code1 values ( 2,'R2 CONTRACTS');
    
    Insert into code1 values ( 3,'R3 CONTRACTS');
    
    Insert into code1 values ( 4,'R5 CONTRACTS');
    
    Insert into code1 values ( 5,'R9 CONTRACTS');
    
    Insert into code1 values ( 6,'R10 CONTRACTS');
    
    create table table1 
    (   
        tablekey number,
        prefix  varchar2(25),
        codedesc    varchar2(60)
    );
    
    Insert into table1(tablekey,prefix) values (1,'1001PAC');
    
    Insert into table1(tablekey,prefix) values (2,'1001MXT');
    
    Insert into table1(tablekey,prefix) values (3,'1002PAE');
    
    Insert into table1(tablekey,prefix) values (4,'1003PCS');
    
    Insert into table1(tablekey,prefix) values (5,'1004BDX');
    
    Insert into table1(tablekey,prefix) values (6,'1005PAC');
    
    Insert into table1(tablekey,prefix) values (7,'1006PAC');
    
    Insert into table1(tablekey,prefix) values (8,'1007LDR');
    
    Insert into table1(tablekey,prefix) values (9,'1009LCR');
    
    Insert into table1(tablekey,prefix) values (10,'1010LBR');
    
    Insert into table1(tablekey,prefix) values (11,'ABCDEF');
    I'm writing a query that would update the value of column - codedesc (currently Null) of the table1 table: after it is a string of column - table code1 codedesc.

    The logic for the match is, - take - 2nd column of table-codedesc code value and get 2 characters. For example, when the string is - R1 CONTRACTS, the string will be 1. (Select substr ("R1 CONTRACTS, 2, 2) of the double). -Output will be 1.

    Now,.
    Look in table 1 for the 3rd position of the prefix that corresponds to the string returned by the query above. So, if the prefix is '1001PAC', it should look for 2 value of figures from the 3rd position. So, in this case it will be 01. Digitally 01 and 1 are equal, then the match is found for this line in the table1 table, so we will need to update the value of the column codedesc with the "contracts of R1.
        tablekey,    prefix            codedesc    
    ---------- ------------------------------------------------------------
    
          1               1001PAC     R1 CONTRACTS    -- Needs to be update with this value. 
          2               1001MXT     R1 CONTRACTS
          3               1002PAE      R2 CONTRACTS
    ...
          11             ABCDEF                                --Null ( No Need to update when no match found).
    SQL> select * from v$version;
    
    BANNER
    ----------------------------------------------------------------
    Oracle Database 10g Release 10.2.0.4.0 - 64bit Production
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for Linux: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    Appreciate your help.

    Hello

    You want to avoid TO_NUMBER, given that will cause an error if even a line has a number no (except space) in the wrong place.
    Use RTRIM to remove extra spaces at the end of the match_key and LPAD to add '0', if necessary, at the beginning:

    MERGE INTO     table1          dst
    USING   (
              SELECT  LPAD ( RTRIM ( SUBSTR ( codedesc
                                     , 2
                                   , 2
                                   )
                              )
                         , 2
                         , '0'
                         )          AS match_key
              ,     codedesc
              FROM     code1
         )               src
    ON     (src.match_key     = SUBSTR ( dst.prefix
                           , 3
                         , 2
                         )
         )
    WHEN MATCHED THEN UPDATE
         SET     dst.codedesc     = src.codedesc
    ;
    

    Thanks for posting the CREATE TABLE and INSERT statements; It's very useful!

Maybe you are looking for