Insert Using SELECT & Sub-SELECT

Hi All,
I am trying to insert records into a table using SELECT statement. The SELECT statement has a Sub-SELECT statement as follows:
INSERT INTO table1(c1,c2,c3,c4,c5)
SELECT c1,c2, (SELECT MAX(C3)+a1.c3
FROM table1
WHERE c1 = var1
AND c2 = a1.c2
GROUP BY c3),c4,c5,
FROM table1 a1
WHERE c1 = var1
The above works fine when run from SQL*PLUS but gives compilation error when included in PL/SQL pacakge.
I am using Oracle 8.1.7.
Could you any one please tell me if I have missed something?
Thanks,
Satyen.

In 8i, you will need to use dynamic SQL to execute this statement because the PL/SQL parser does not understand all SQL syntax (including SELECT in a column list).
execute immediate
  'INSERT INTO table1(c1,c2,c3,c4,c5)' ||
  ' SELECT c1, c2, (SELECT MAX(C3)+a1.c3 FROM table1 WHERE c1 = :var1 AND c2 = a1.c2 GROUP BY c3), c4, c5' ||
  '   FROM table1 a1 WHERE c1 = :var1' using var1, var1;

Similar Messages

  • Proper insert using a sub select

    I have always used:
    insert into table_x (field_1, field_2)
    select 'data_for_field_1', data_for_field_2 from
    table_y;
    This works no matter what.
    I have identified the following insert that works in 8i but not 8.0.5:
    insert into table_x (field_1, field_2)
    values ('data_for_field_1', (select data_for_field_2 from
    table_y));
    Can someone please tell me why this insert is a no no. I would greatly appreciate any logic on how the db engine processes this kind of statement, why it works in 8i but not lesser versions, or simply an argument why not to do this.
    Thanks a bunch.

    Why it works in 8.1 but not in lesser versions? Becaue Oracle enhances SQL in each version.

  • Delete statement that uses a sub-select with the statement in the cursor

    Hi all,
    How to write write a delete statement that uses a sub-select with the statement in the cursor?
    CURSOR excluded_dates IS         
           SELECT TO_TIMESTAMP(report_parameter_value, in_date_format_mask)
          INTO my_current_date_time
          FROM report_parameters
         WHERE report_parameters.report_parameter_id    = in_report_parameter_id
           AND report_parameters.report_parameter_group = 'DATE_TIME'
           AND report_parameters.report_parameter_name  = 'EXCLUDED_DATE';
    OPEN excluded_dates;
      LOOP
        FETCH excluded_dates INTO my_excluded_date;
        EXIT WHEN excluded_dates%NOTFOUND;
        DELETE FROM edr_rpt_tmp_inclusion_table
        WHERE TO_CHAR(date_time, 'mm/dd/yyyy') = TO_CHAR(my_excluded_date, 'mm/dd/yyyy');
      END LOOP;
      CLOSE excluded_dates;Thanks

    Hi,
    In such case I think is better to create a view an perform the delete using it. Example (using HR schema):
    Connected to Oracle Database 10g Express Edition Release 10.2.0.1.0
    Connected as hr
    SQL> create or replace view v_employees as select * from employees where first_name like 'J%';
    View created
    SQL> select * from v_employees;
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE   JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID
            110 John                 Chen                      JCHEN                     515.124.4269         28/09/1997  FI_ACCOUNT    8200,00                       108           100
            112 Jose Manuel          Urman                     JMURMAN                   515.124.4469         07/03/1998  FI_ACCOUNT    7800,00                       108           100
            125 Julia                Nayer                     JNAYER                    650.124.1214         16/07/1997  ST_CLERK      3200,00                       120            50
            127 James                Landry                    JLANDRY                   650.124.1334         14/01/1999  ST_CLERK      2400,00                       120            50
            131 James                Marlow                    JAMRLOW                   650.124.7234         16/02/1997  ST_CLERK      2500,00                       121            50
            133 Jason                Mallin                    JMALLIN                   650.127.1934         14/06/1996  ST_CLERK      3300,00                       122            50
            139 John                 Seo                       JSEO                      650.121.2019         12/02/1998  ST_CLERK      2700,00                       123            50
            140 Joshua               Patel                     JPATEL                    650.121.1834         06/04/1998  ST_CLERK      2500,00                       123            50
            145 John                 Russell                   JRUSSEL                   011.44.1344.429268   01/10/1996  SA_MAN       14000,00           0,40        100            80
            156 Janette              King                      JKING                     011.44.1345.429268   30/01/1996  SA_REP       10000,00           0,35        146            80
            176 Jonathon             Taylor                    JTAYLOR                   011.44.1644.429265   24/03/1998  SA_REP        8600,00           0,20        149            80
            177 Jack                 Livingston                JLIVINGS                  011.44.1644.429264   23/04/1998  SA_REP        8400,00           0,20        149            80
            181 Jean                 Fleaur                    JFLEAUR                   650.507.9877         23/02/1998  SH_CLERK      3100,00                       120            50
            186 Julia                Dellinger                 JDELLING                  650.509.3876         24/06/1998  SH_CLERK      3400,00                       121            50
            189 Jennifer             Dilly                     JDILLY                    650.505.2876         13/08/1997  SH_CLERK      3600,00                       122            50
            200 Jennifer             Whalen                    JWHALEN                   515.123.4444         17/09/1987  AD_ASST       4400,00                       101            10
    16 rows selected
    SQL> delete from v_employees where hire_date >= to_date('01/06/1998', 'dd/mm/yyyy');
    2 rows deleted
    SQL> regards,

  • How use insert more than query (select)

    insert into FISH_FAMILIES (id,code ,SCIENCE_NAME,ARABIC_NAME,LATIN_NAME,IS_FAMILY)
    SELECT ROWNUM,to_char(ROWNUM) FROM dual CONNECT BY LEVEL <= 43,
    select distinct FAMILY, ARABIC_DESCRIPTION,LATIN_DESCRIPTION from FISH_SPECIES ,
    select distinct IS_FAMILY from FISH_SPECIES
    iam dont know format insert use
    More than select ??????

    ali_alkomi wrote:
    ORA-01427: single-row subquery returns more than one row
    insert into FISH_FAMILIES(SCIENCE_NAME,ARABIC_NAME,LATIN_NAME,IS_FAMILY)
    values ( (select distinct FAMILY from FISH_SPECIES) ,(select ARABIC_DESCRIPTION from FISH_SPECIES) ,(select LATIN_DESCRIPTION from FISH_SPECIES),(select distinct IS_FAMILY from FISH_SPECIES
    ))You were given an answer to that over on your other question:
    How Generating Series Of Numbers Without  use Sequences
    If you are haivng a problem understanding the answers, do not start a new thread, otherwise the same people who were helping you originally may not know you are still having a problem.
    To insert multiple rows of data you cannot use the VALUES clause of the INSERT statement (as it tells you in the documentation if you read it).
    You need:
    INSERT INTO ...
    SELECT ... FROM ... UNION ALL
    SELECT ... FROM ... UNION ALL
    SELECT ... FROM ... etc.or, in your case you would need something more simply like
    insert into FISH_FAMILIES(SCIENCE_NAME,ARABIC_NAME,LATIN_NAME,IS_FAMILY)
    select fs.family, fs.arabic_description, fs.latin_description, fs.is_family
    from   fish_species fs

  • Sub-SELECT in Bulk INSERT- Performance Clarification

    I have 2 tables- emp_new & emp_old. I need to load all data from emp_old to emp_new. There is a transaction_id column in emp_new whose value needs to be fetched from a main_transaction table which also includes a Region Code column. Something like -
    TRANSACTION_ID REGION_CODE
    100 US
    101 AMER
    102 APAC
    My bulk insert query looks like this -
    INSERT INTO emp_new
    (col1,
    col2,
    transaction_id)
    SELECT
    col1,
    col2,
    *(select transaction_id from main_transaction where region_code = 'US')*
    FROM emp_old
    There would be millions of rows which need to be loaded in this way. I would like to know if the sub-SELECT to fetch the transaction_id would be re-executed for every row, which would be very costly and I'm actually looking for a way to avoid this. The main_transcation table is a pre-loaded table and its values are not going to change. Is there a way (via some HINT) to indicate that the sub-SELECT should not get re-executed for every row ?
    On a different note, the execution plan of the above bulk INSERT looks like -
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)|
    | 0 | INSERT STATEMENT | | 11M| 54M| 6124 (4)|
    | 1 | INDEX FAST FULL SCAN| EMPO_IE2_IDX | 11M| 54M| 6124 (4)|
    EMPO_IE2_IDX -> Index on emp_old
    I'm surprised to see that the table main_transaction does not feature in the execution plan at all. Does this mean that the sub-SELECT will not get re-executed for every row? However, atleast for the first read, I would assume that the table should appear in the plan.
    Can someone help me in understanding this ?

    Dear
    From 10.2, AUTOTRACE uses DBMS_XPLAN anywayYes but with the remark that it uses the estimated part of DBMS_XPLAN i.e explain plan for + select * from table(dbms_xplan.display);
    Isn'it ?
    mhouri> cl scr
    mhouri> desc t
    Name                    Null?    Type
    ID                               VARCHAR2(10)
    NAME                             VARCHAR2(100)
    mhouri> set linesize 150
    mhouri> var x number
    mhouri> exec :x:=99999
    PL/SQL procedure successfully completed.
    mhouri> explain plan for
      2  select sum(length(name)) from t where id >  :x;
    Explained.
    mhouri> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT                                                                                                                                    
    Plan hash value: 1188118800                                                                                                                          
    | Id  | Operation                    | Name | Rows  | Bytes | Cost (%CPU)| Time     |                                                                
    |   0 | SELECT STATEMENT             |      |     1 |    23 |     4   (0)| 00:00:01 |                                                                
    |   1 |  SORT AGGREGATE              |      |     1 |    23 |            |          |                                                                
    |   2 |   TABLE ACCESS BY INDEX ROWID| T    |    58 |  1334 |     4   (0)| 00:00:01 |                                                                
    |*  3 |    INDEX RANGE SCAN          | I    |    11 |       |     2   (0)| 00:00:01 |                                                                
    PLAN_TABLE_OUTPUT                                                                                                                                    
    Predicate Information (identified by operation id):                                                                                                  
       3 - access("ID">:X)                                                                                                                               
    15 rows selected.
    mhouri> set autotrace on
    mhouri> select sum(length(name)) from t where id >  :x;
    SUM(LENGTH(NAME))                                                                                                                                    
                10146                                                                                                                                    
    Execution Plan
    Plan hash value: 1188118800                                                                                                                          
    | Id  | Operation                    | Name | Rows  | Bytes | Cost (%CPU)| Time     |                                                                
    |   0 | SELECT STATEMENT             |      |     1 |    23 |     4   (0)| 00:00:01 |                                                                
    |   1 |  SORT AGGREGATE              |      |     1 |    23 |            |          |                                                                
    |   2 |   TABLE ACCESS BY INDEX ROWID| T    |    58 |  1334 |     4   (0)| 00:00:01 |                                                                
    |*  3 |    INDEX RANGE SCAN          | I    |    11 |       |     2   (0)| 00:00:01 |                                                                
    Predicate Information (identified by operation id):                                                                                                  
       3 - access("ID">:X)                                                                                                                               
    Statistics
              0  recursive calls                                                                                                                         
              0  db block gets                                                                                                                           
             15  consistent gets                                                                                                                         
              0  physical reads                                                                                                                          
              0  redo size                                                                                                                               
            232  bytes sent via SQL*Net to client                                                                                                        
            243  bytes received via SQL*Net from client                                                                                                  
              2  SQL*Net roundtrips to/from client                                                                                                       
              0  sorts (memory)                                                                                                                          
              0  sorts (disk)                                                                                                                            
              1  rows processed                                                                                                                          
    mhouri> set autotrace off
    mhouri> select sum(length(name)) from t where id >  :x;
    SUM(LENGTH(NAME))                                                                                                                                    
                10146                                                                                                                                    
    mhouri> select * from table(dbms_xplan.display_cursor);
    PLAN_TABLE_OUTPUT                                                                                                                                    
    SQL_ID  7zm570j6kj597, child number 0                                                                                                                
    select sum(length(name)) from t where id >  :x                                                                                                       
    Plan hash value: 1842905362                                                                                                                          
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |                                                                          
    |   0 | SELECT STATEMENT   |      |       |       |     5 (100)|          |                                                                          
    |   1 |  SORT AGGREGATE    |      |     1 |    23 |            |          |                                                                          
    |*  2 |   TABLE ACCESS FULL| T    |    59 |  1357 |     5   (0)| 00:00:01 |                                                                          
    Predicate Information (identified by operation id):                                                                                                  
       2 - filter(TO_NUMBER("ID")>:X)                                                                                                                    
    19 rows selected.
    mhouri> spool offBest regards
    Mohamed Houri

  • Number of rows inserted is different in bulk insert using select statement

    I am facing a problem in bulk insert using SELECT statement.
    My sql statement is like below.
    strQuery :='INSERT INTO TAB3
    (SELECT t1.c1,t2.c2
    FROM TAB1 t1, TAB2 t2
    WHERE t1.c1 = t2.c1
    AND t1.c3 between 10 and 15 AND)' ....... some other conditions.
    EXECUTE IMMEDIATE strQuery ;
    These SQL statements are inside a procedure. And this procedure is called from C#.
    The number of rows returned by the "SELECT" query is 70.
    On the very first time call of this procedure, the number rows inserted using strQuery is *70*.
    But in the next time call (in the same transaction) of the procedure, the number rows inserted is only *50*.
    And further if we are repeating calling this procedure, it will insert sometimes 70 or 50 etc. It is showing some inconsistency.
    On my initial analysis it is found that, the default optimizer is "ALL_ROWS". When i changed the optimizer mode to "rule", this issue is not coming.
    Anybody faced these kind of issues?
    Can anyone tell what would be the reason of this issue..? any other work around for this...?
    I am using Oracle 10g R2 version.
    Edited by: user13339527 on Jun 29, 2010 3:55 AM
    Edited by: user13339527 on Jun 29, 2010 3:56 AM

    You have very likely concurrent transactions on the database:
    >
    By default, Oracle Database permits concurrently running transactions to modify, add, or delete rows in the same table, and in the same data block. Changes made by one transaction are not seen by another concurrent transaction until the transaction that made the changes commits.
    >
    If you want to make sure that the same query always retrieves the same rows in a given transaction you need to use transaction isolation level serializable instead of read committed which is the default in Oracle.
    Please read http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10471/adfns_sqlproc.htm#ADFNS00204.
    You can try to run your test with:
    set  transaction isolation level  serializable;If the problem is not solved, you need to search possible Oracle bugs on My Oracle Support with keywords
    like:
    wrong results 10.2Edited by: P. Forstmann on 29 juin 2010 13:46

  • Using XML in sub select

    Hmmmm
    Stuck again, it seems as though I am not the sharpest tool in the box when it comes to XML. Boss seems to love XML though....
    In SQL I have the ability to do something similar to the following :
    SELECT * FROM JOBS
    WHERE JOB_ID IN(SELECT JOB_ID WHERE ACTIVE = 1)
    In this scenario no real need to do a sub select however it demonstrates my point.
    Is it possible to achive this using an XML document in my sub select?
    eg something like
    SELECT * FROM JOBS WHERE JOB_ID IN(EXTRACTVALUE(var,xpath JOB_ID)
    If I had a big list would this iterate through each instance of the value I want to join on???

    Have a look at the XML DB technical whitepaper
    http://otn.oracle.com/tech/xml/xmldb/Current/TWP.pdf
    QUERYING AND INDEXING XML WITH ORACLE XML DB on Page 49
    In particular the queries on Page 51

  • Can I do an Insert using two selects from different tables?

    Hi,
    I have three tables, Course (CID, NAME, TIME)
    Teacher (TID, NAME, DESCRIPTION) and OfferedBy(CID, TID) to match a course to a teacher.
    After I do an insert on Course, I want to be able to do an insert on OfferedBy using the CID of the course I inserted, and the TID of the teacher that's offering it.
    I tried this after doing inserts on Course and Teacher:
    INSERT INTO OfferedBy values (SELECT CID FROM Course where courseName = 'name' , SELECT TID FROM Teacher WHERE LastName = 'teacherName').
    I get an ORA 00907 error.
    What am I doing wrong? Can this actually be done?
    Thank you
    I

    Hi,
    How would you relate the TID with CID?
    I tried this after doing inserts on Course and Teacher:
    INSERT INTO OfferedBy values (SELECT CID FROM Course where courseName >= 'name' , SELECT TID FROM Teacher WHERE LastName = 'teacherName').
    I get an ORA 00907 error.You can use the query in this way:
    SQL> SELECT ( ( SELECT dummy FROM DUAL), (SELECT DUMMY FROM DUAL)) FROM DUAL;
    SELECT ( ( SELECT dummy FROM DUAL), (SELECT DUMMY FROM DUAL)) FROM DUAL
    ERROR at line 1:
    ORA-00907: missing right parenthesis
    SQL> SELECT 'AA',(SELECT dummy FROM DUAL) FROM DUAL;
    'A (
    AA X
    SQL>Regards

  • What mechanism Oracle 10g use for write (Insert/ Update) and Read (Select)?

    Hi
    What mechanism Oracle 10g use for write (Insert/ Update) and Read (Select)?
    Thank you

    Aren't the answers given in PL/SQL forum sufficient enough?Well, as the first answer in that forum directed the OP to this forum you can hardly blame them for the repost.
    There is some high-level stuff in the Concepts Guide. If that is insufficient the OP will need to tell us what more details they need to know (and perhaps why).
    Cheers, APC

  • Using an Aggregate Function in a Sub-SELECT

    Ok. I have this Sub-SELECT and I'd like to base my outside query based on the resyult set of my inner Sub-SELECT which contains an Aggregate function.
    Is that possible???
    Here's the Query...
    SELECT *
    FROM CUSTPRO.CPM_PND_TRAN_HDR CPMPNDTH
    INNER JOIN (SELECT CPMPNDT2.ky_pnd_seq_trans,
    CPMPNDT2.id_ba_esco,
    CPMPNDT2.ky_ba,
    CPMPNDT2.ky_enroll,
    MAX(CPMPNDT2.dt_billed_by_css)
    FROM CUSTPRO.CPM_PND_TRAN_HDR CPMPNDT2
    WHERE CPMPNDT2.ky_pnd_seq_trans IN (6544937)
    GROUP BY CPMPNDT2.ky_pnd_seq_trans,
    CPMPNDT2.id_ba_esco,
    CPMPNDT2.ky_ba,
    CPMPNDT2.ky_enroll) DERIVE1
    ON CPMPNDTH.id_ba_esco = DERIVE1.id_ba_esco
    AND CPMPNDTH.ky_ba = DERIVE1.ky_ba
    AND CPMPNDTH.ky_enroll = DERIVE1.ky_enroll
    AND CPMPNDTH.dt_billed_by_css = ????DERIVE1.MAX(CPMPNDT2.dt_billed_by_css)???
    How can I designate that last qualifier ????....
    PSULionRP

    You should give your aggregate function a column-alias as in:
    SELECT *
    FROM   custpro.cpm_pnd_tran_hdr cpmpndth
           INNER JOIN (SELECT   cpmpndt2.ky_pnd_seq_trans,
                                cpmpndt2.id_ba_esco,
                                cpmpndt2.ky_ba,
                                cpmpndt2.ky_enroll,
                                Max(cpmpndt2.dt_billed_by_css) as XXX    -- ADDED THIS.
                       FROM     custpro.cpm_pnd_tran_hdr cpmpndt2
                       WHERE    cpmpndt2.ky_pnd_seq_trans IN (6544937)
                       GROUP BY cpmpndt2.ky_pnd_seq_trans,
                                cpmpndt2.id_ba_esco,
                                cpmpndt2.ky_ba,
                                cpmpndt2.ky_enroll) derive1
             ON cpmpndth.id_ba_esco = derive1.id_ba_esco
                AND cpmpndth.ky_ba = derive1.ky_ba
                AND cpmpndth.ky_enroll = derive1.ky_enroll
                AND cpmpndth.dt_billed_by_css = derive1.XXX
    /

  • Sub-Select Count query breaking TOAD

    Oracle 10.2.0.4.0
    Running TOAD 9.1
    I am running some SQL on our eBusiness Suite:
    SELECT pha.segment1
         , pha.type_lookup_code
         , (SELECT COUNT(DISTINCT pha2.po_header_id)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) po_count
         , (SELECT MAX(pha2.creation_date)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) latest_cpa_po
      FROM po.po_headers_all pha
         , po.po_vendors pv
         , po.po_vendor_sites_all pvsa
    WHERE pha.vendor_id = pv.vendor_id
       AND pha.vendor_site_id = pvsa.vendor_site_id
    --   AND pv.VENDOR_NAME LIKE 'H%'
       AND pha.vendor_id = 98
       AND pha.type_lookup_code = 'CONTRACT'
       AND pha.org_id IN(7041, 7042);The above query runs quicky (approx. 1 second). If I take out the AND pha.vendor_id = 98 then the query takes a few minutes to run.
    When I try to export it, or scroll down to view > 500 rows, TOAD crashes.
    I know this isn't a TOAD forum, but I think that this is probably an issue with my no doubt rubbish SQL.
    If I take out this sub-select, then the problem doesn't happen:
         , (SELECT COUNT(DISTINCT pha2.po_header_id)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) po_countHowever, I can't work out a better way of getting the data I need.
    The sub-select counts POs which have been raised where the contractID on the PO line is the same as the PO Header ID from the main query.
    Any advice please, on what I could do to sort this out would be much appreciated.
    Thanks!

    Hi,
    It looks like you can replace both scalar sub-queries with a join, like this:
    WITH     header_lines_summary     AS
         SELECT    pla.contract_id
              ,       COUNT (DISTINCT pha2.po_header_id)     AS po_count
              ,       MAX (pha2.creation_date)          AS latest_cpa_po
              FROM        po.po_headers_all pha2
                 ,        po.po_lines_all   pla
             WHERE        pha2.po_header_id = pla.po_header_id
          GROUP BY       pla.contract_id
    )                                        -- Everything up to this line is new
    SELECT pha.segment1
         , pha.type_lookup_code
         , hls.po_count                              -- Changed
         , hls.latest_cpa_po                         -- Changed
      FROM po.po_headers_all     pha
         , po.po_vendors           pv
         , po.po_vendor_sites_all      pvsa
         , header_lines_summary     hls                    -- New
    WHERE pha.vendor_id          = pv.vendor_id
       AND pha.vendor_site_id     = pvsa.vendor_site_id
       AND pha.po_header_id          = hls.contract_id (+)          -- New
    --   AND pv.VENDOR_NAME      LIKE 'H%'
       AND pha.vendor_id           = 98
       AND pha.type_lookup_code      = 'CONTRACT'
       AND pha.org_id           IN (7041, 7042);Aside from the sub-query (which is entirely new), the query above is just what you posted, with 2 lines changed and 2 lines added, as marked.
    This should be more efficient, but I don't know for certain that it will solve the Toad problem.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
    It never hurts to say what version of Oracle you're using.

  • Sub select query Help

    I have to do a task of finding records which matches the following logic.
    My table has PID varchar(15), Amount varchar (50),Status varchar(20) columns.
    Each PID can go thru changes in a period of time, in my case i dont have a data range I just have a flatfile which consists of three types of PID`s
    123456 = Original_PID, Reversal =123456R1,Adjustment= 123456A1.
    Basically What I am trying to find out if there are any original PID`s which has a Reversal or an Adjustment.
    here`s the code I have started on... Can someone help me get it finished?
    select R1. pid,a1.pid,org.pid from (
    select SUBSTRING(Pid,1,11)as Original_PID, status, paid_amount as Amount from dbo.Q2STATUS)org
    inner join (select SUBSTRING(Pid,1,13)as Original_Icn,status,paid_amount from dbo.Q2STATUS
    where SUBSTRING(Pid,12,2) ='R1')r1 on r1.pid=org.pid
    inner join (select SUBSTRING(claim_id,1,13)as Original_Icn,status,paid_amount from dbo.Q2STATUS
    where SUBSTRING(Pid,12,2) ='A1')A1 on a1.Pid=org.PID
    FM

    Hi,
    Please check following item
    It uses a
    SQL string function, please create it first
    create table Q2STATUS (Pid nvarchar(200), Status varchar(20), paid_amount int)
    insert into Q2STATUS select '123456 = Original_PID, Reversal =123456R1, Adjustment= 123456A1',NULL,250
    with cte2 as (
    select rn = row_number() over (order by pid), * from Q2STATUS
    ), cte as (
    select cte2.*, s.id typeid, v.*
    from cte2
    cross apply dbo.split(cte2.Pid, ',') s
    cross apply dbo.split(s.val, '=') v
    ), cte3 as (
    select
    rn, pid, status, paid_amount, max(pidtype) pidtype, max(pidval) pidval
    from (
    select
    rn, Pid, status, paid_amount, typeid,
    case when (typeid = 1 and id = 2) or (typeid <> 1 and id = 1) then ltrim(rtrim(val)) else null end as pidtype,
    case when (typeid = 1 and id = 1) or (typeid <> 1 and id = 2) then ltrim(rtrim(val)) else null end as pidval
    from cte
    ) g
    group by rn, pid, status, paid_amount, typeid
    select
    cte2.rn, cte2.pid,
    cte3.pidval as 'Original_PID',
    cte4.pidval as 'Reversal',
    cte5.pidval as 'Adjustment'
    from cte2
    left join cte3 on cte3.rn = cte2.rn and pidtype = 'Original_PID'
    left join cte3 as cte4 on cte4.rn = cte2.rn and cte4.pidtype = 'Reversal'
    left join cte3 as cte5 on cte5.rn = cte2.rn and cte5.pidtype = 'Adjustment'
    Here is the result,
    Please note that I have used
    SQL CTE expressions a lot in the SQL query to prevent usage of sub-select and temp tables.
    There is also a
    SQL ROW_NUMBER() function used in the first SELECT statement to distinquish all items from each other instead of using the PID column value. Perhaps you have already an ID key column, you can use it too
    SQL Server, SQL Server 2012 Denali and T-SQL Tutorials

  • T-SQL - PL/SQL conversion: insert into ... select problem

    Hi!
    If I have an insert into ... select statement in T-SQL without a 'from' clause:
    bq. insert into sometable (foo, bar) \\ select 5, case when @bar=5 then 4 else 3 end
    its translation is:
    bq. INSERT INTO sometable \\ ( foo, bar ) \\ VALUES ( 5, CASE \\ WHEN 5 = 5 THEN 4 \\ ELSE 3 \\ END col );
    and I got: ORA-00917: "missing comma" for that. I'm not sure if it's a bug in the migration code, or is there a trick so that I can use 'CASE' in an insert into .. values statement somehow?
    Zoli

    You have to remove the column name. I just simplified your test case to check and it's working:
    CREATE TABLE test(
      id NUMBER
    INSERT
      INTO test(id)
      VALUES(CASE WHEN 5=5 THEN 4 ELSE 3 END)
    SELECT *
      FROM test
    ;C.

  • Using procedure in SELECT statement

    I have a select statement that currently uses 4 functions to receive necessary values. All the functions are recursive and returns values from the same row.
    What I would like to do is replace these for function calls with 1 procedure. Does anybody know if it possible to use a procedure in this way inside a select statement?
    If so, do you have the syntax for doing this?
    E.g
    SELECT
    Mdbrd_Pkg.calculate_fixed_charge_fn(in_rc_id, ap.CONFIGSET_ID) AS FIXED_CHARGE,
    Mdbrd_Pkg.calculate_charge_rate_fn(in_rc_id, ap.CONFIGSET_ID) AS CHARGE_RATE,
    Mdbrd_Pkg.tax_liable_fn(in_rc_id, ap.CONFIGSET_ID) AS TAX_LIABLE,
    Mdbrd_Pkg.charge_unit_fn( in_rc_id, ap.CONFIGSET_ID) AS CHARGEUNIT_ID
    FROM .....

    This cannot be done. The part of the function used in the SELECT statement is the return value: procedures don't have return values (that's what makes tham procedures and not functions).
    Obviously I don't know what your code does, but you should consider putting them into a single function that returns a TYPE with four attributes and then using the TABLE() function to cast them into something you could reference in the FROM clause of a correlated sub-query. Sounds a bit messy though.
    Do these functions actually select data? Where does the recursion fit in?
    Cheers, APC

  • Sub selects in a SQL statement

    Hi, I have a query with an obsene amount of sub selects,
    for example :
    SELECT p.ID,
    (select something from data where id = p.id) data1,
    (select somelse from data2 where id = p.id) data2,
    (select someelse from data3 where id = p.id) data3,
    (select someelse from data4 where id = p.id) data4,
    (select someelse from data5 where id = p.id) data5,
    FROM property P
    WHERE ..........
    this query is taking a long time to process. Is there a more efficient way of doing such a statement?
    thanks in advance

    Gabe:
    Since the original poster said "this query is taking a long time to process", I assumed that there was a one-to-one relationship between properties and each of the dataX tables, otherwise, as you pointed out, he would be complaining about ORA-01427: single-row subquery returns more than one row
    In my union, I am returning a single column from each of the data tables (plus the id), and a NULL for each of the other columns in the in-line view. The MAX function just gets the single row for each column that actually has a value.
    As a test case, I did:
    CREATE TABLE properties AS
    SELECT rownum id, object_name
    FROM all_objects
    WHERE rownum < 11;
    CREATE TABLE data1 (id NUMBER, descr VARCHAR2(10));
    INSERT INTO data1 VALUES(1, 'ONE');
    INSERT INTO data1 VALUES(2, 'TWO');
    INSERT INTO data1 VALUES(3, 'THREE');
    CREATE TABLE data2 (id NUMBER, descr VARCHAR2(10));
    INSERT INTO data2 VALUES(4, 'FOUR');
    INSERT INTO data2 VALUES(5, 'FIVE');
    INSERT INTO data2 VALUES(6, 'SIX');
    CREATE TABLE data3 (id NUMBER, descr VARCHAR2(10));
    INSERT INTO data3 VALUES(7, 'SEVEN');
    INSERT INTO data3 VALUES(8, 'EIGHT');
    INSERT INTO data3 VALUES(9, 'NINE');The original version as posted retrieves:
    SQL> SELECT p.id, p.object_name,
      2         (SELECT descr FROM data1 WHERE id = p.id) data1,
      3         (SELECT descr FROM data2 WHERE id = p.id) data2,
      4         (SELECT descr FROM data3 WHERE id = p.id) data3
      5  FROM properties p
      6  ORDER BY p.id;
            ID OBJECT_NAME                    DATA1      DATA2      DATA3
             1 TAB$                           ONE
             2 I_IND1                         TWO
             3 I_COBJ#                        THREE
             4 USER$                                     FOUR
             5 I_OBJ1                                    FIVE
             6 I_PROXY_ROLE_DATA$_2                      SIX
             7 BOOTSTRAP$                                           SEVEN
             8 I_ICOL1                                              EIGHT
             9 UNDO$                                                NINE
            10 PROXY_ROLE_DATA$
    10 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             93 consistent gets
              0  physical reads
              0  redo size
           1000  bytes sent via SQL*Net to client
            655  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             10  rows processedBut, it does a SELECT (hopefully indexed) of data1, data2, and data3 for each row in properties. Minimally, 9 gets per row of properties (index root, index leaf, table row for each of data1, data2, data3) without even getting any data from properties.
    My query returns:
    SQL> SELECT p.id, p.object_name, a.data1, a.data2, a.data3
      2  FROM properties p,
      3       (SELECT id, MAX(data1) data1, MAX(data2) data2, MAX(data3) data3
      4        FROM (SELECT id, descr data1, TO_CHAR(NULL) data2, TO_CHAR(NULL) data3
      5              FROM data1
      6              UNION ALL
      7              SELECT id, TO_CHAR(NULL), descr, TO_CHAR(NULL)
      8              FROM data2
      9              UNION ALL
    10              SELECT id, TO_CHAR(NULL), TO_CHAR(NULL), descr
    11              FROM data3)
    12        GROUP BY id) a
    13  WHERE p.id = a.id(+)
    14  ORDER BY p.id;
            ID OBJECT_NAME                    DATA1      DATA2      DATA3
             1 TAB$                           ONE
             2 I_IND1                         TWO
             3 I_COBJ#                        THREE
             4 USER$                                     FOUR
             5 I_OBJ1                                    FIVE
             6 I_PROXY_ROLE_DATA$_2                      SIX
             7 BOOTSTRAP$                                           SEVEN
             8 I_ICOL1                                              EIGHT
             9 UNDO$                                                NINE
            10 PROXY_ROLE_DATA$
    10 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             12 consistent gets
              0  physical reads
              0  redo size
           1000  bytes sent via SQL*Net to client
            655  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              2  sorts (memory)
              0  sorts (disk)
             10  rows processedThe same result, but 1/8 of the gets. an outer join is also possible:
    SQL> SELECT p.id, p.object_name, d1.descr data1, d2.descr data2, d3.descr data3
      2  FROM properties p, data1 d1, data2 d2, data3 d3
      3  WHERE p.id = d1.id(+) AND
      4        p.id = d2.id(+) AND
      5        p.id = d3.id(+)
      6  ORDER BY p.id;
            ID OBJECT_NAME                    DATA1      DATA2      DATA3
             1 TAB$                           ONE
             2 I_IND1                         TWO
             3 I_COBJ#                        THREE
             4 USER$                                     FOUR
             5 I_OBJ1                                    FIVE
             6 I_PROXY_ROLE_DATA$_2                      SIX
             7 BOOTSTRAP$                                           SEVEN
             8 I_ICOL1                                              EIGHT
             9 UNDO$                                                NINE
            10 PROXY_ROLE_DATA$
    10 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             12 consistent gets
              0  physical reads
              0  redo size
           1000  bytes sent via SQL*Net to client
            655  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             10  rows processedSo, the same number of gets, and it saves one sort. But if the tables are large, multiple outer joins may not be as efficient as one outer join to the union all query.
    HTH
    John

Maybe you are looking for