Use UNION / Append in PL/SQL

Hello,
I am using Oracle 11g R2 SOE. I have this procedure, and I would like to *"UNION" its* Select Statement with another Select Statement:
declare
  v_xml clob;
  v_retval clob := '<?xml version="1.0" encoding="iso-8859-1"?>';
  v_blob blob;
begin
select
       xmlelement(
         "LISTINGS",
         xmlagg(
           xmlelement(
             "LISTING",
             xmlforest(
'RS-'||R."RES_ID" as "Property_Ref_No",
"UNIT_TYPE_LOOKUP"."UNIT_TYPE" as "Unit_Type",
'Sale' as "Ad_Type",
'Dubai' as "State",
L.LOCATION_NAME_EN AS "Community",
"PROJECTS"."PROJECT_NAME_EN" as "Property_Name",
"RES_SALE"."ASKING_PRICE" as "Price",
' ' as "Frequency",
ST."SUB_TYPE" as "Unit_Model",
R."RES_SIZE" as "Unit_Builtup_Area",
R.BEDS as "Bedrooms",
R.bath as "No_of_Bathrooms",
"RES_SALE"."AD_TITLE" as "Property_Title",
RES_SALE.DESCRIPTION as "Web_Remarks",
to_char("RES_SALE"."UPDATED_ON",'YYYY-MM-DD HH:MI:SSPM') as "Last_Updated",
R.VIDEO as "Web_Tour",
select xmlagg(
                             xmlforest(
                            'http://thevillaproject.com/apex/erp/IMAGES/'||IMG.ID AS "ImageUrl"
FROM      
      IMAGES IMG     
WHERE IMG.RES_ID = R.RES_ID ) Images )))).getclobval()
  into      v_xml
  FROM
      "RES_SALE" "RES_SALE"
inner join
      RES R on (R."RES_ID"="RES_SALE"."RES_ID")
inner join
          "UNIT_STATUS_LOOKUP" on (UNIT_STATUS_LOOKUP.status_id = "RES_SALE"."RES_STATUS")
inner join
      "PROJECTS" "PROJECTS" on ("PROJECTS"."PROJECT_ID"=R."PROJECT_ID")
inner join
      "UNIT_TYPE_LOOKUP" "UNIT_TYPE_LOOKUP" on ("UNIT_TYPE_LOOKUP"."TYPE_ID"=R."RES_TYPE")
inner join
      "RES_SUB_TYPE_LOOKUP" ST on (ST."SUB_TYPE_ID"=R."SUB_TYPE")
INNER JOIN
      COMPLEX_LOOKUP CL ON (CL.COMPLEX_ID = "PROJECTS".COMPLEX_ID)
INNER JOIN
      LOCATIONS L ON (L.LOCATION_ID = CL.LOCATION_ID)
WHERE  "RES_SALE".RES_status IN (5,8) AND "RES_SALE".LIVE = 'Y' AND "RES_SALE".DESCRIPTION IS NOT NULL
  dbms_lob.append(v_retval,v_xml);
  OWA_UTIL.Mime_Header('text/xml'); 
  htp.p('Content-length: ' || to_char(dbms_lob.getlength(v_retval)));
  htp.p('Content-Disposition:  inline; filename="Just.xml"');
  owa_util.http_header_close;
  v_blob := wwv_flow_utilities.clob_to_blob(v_retval);
  wpg_docload.download_file(v_blob);
end; h1. Select Statement that is needed to be "UNION-ED" with the Select Statement of the previous procedure:
select
       xmlelement(
         "LISTINGS",
         xmlagg(
           xmlelement(
             "LISTING",
             xmlforest(
'RR-'||R."RES_ID" as "Property_Ref_No",
"UNIT_TYPE_LOOKUP"."UNIT_TYPE" as "Unit_Type",
'Rent' as "Ad_Type",
'Dubai' as "State",
L.LOCATION_NAME_EN AS "Community",
"PROJECTS"."PROJECT_NAME_EN" as "Property_Name",
"RES_RENT"."ASKING_PRICE" as "Price",
' ' as "Frequency",
ST."SUB_TYPE" as "Unit_Model",
R."RES_SIZE" as "Unit_Builtup_Area",
R.BEDS as "Bedrooms",
R.bath as "No_of_Bathrooms",
"RES_RENT"."AD_TITLE" as "Property_Title",
"RES_RENT".DESCRIPTION as "Web_Remarks",
to_char("RES_RENT"."UPDATED_ON",'YYYY-MM-DD HH:MI:SSPM') as "Last_Updated",
R.VIDEO as "Web_Tour",
select xmlagg(
                             xmlforest(
                            'http://thevillaproject.com/apex/erp/IMAGES/'||IMG.ID AS "ImageUrl"
FROM      
      IMAGES IMG     
WHERE IMG.RES_ID = R.RES_ID ) Images ))))
FROM
      "RES_RENT" "RES_RENT"
inner join
      RES R on (R."RES_ID"="RES_RENT"."RES_ID")
inner join
          "UNIT_STATUS_LOOKUP" on (UNIT_STATUS_LOOKUP.status_id = "RES_RENT"."RES_STATUS")
inner join
      "PROJECTS" "PROJECTS" on ("PROJECTS"."PROJECT_ID"=R."PROJECT_ID")
inner join
      "UNIT_TYPE_LOOKUP" "UNIT_TYPE_LOOKUP" on ("UNIT_TYPE_LOOKUP"."TYPE_ID"=R."RES_TYPE")
inner join
      "RES_SUB_TYPE_LOOKUP" ST on (ST."SUB_TYPE_ID"=R."SUB_TYPE")
INNER JOIN
      COMPLEX_LOOKUP CL ON (CL.COMPLEX_ID = "PROJECTS".COMPLEX_ID)
INNER JOIN
      LOCATIONS L ON (L.LOCATION_ID = CL.LOCATION_ID)
WHERE  "RES_RENT".RES_status IN (5,8) AND "RES_RENT".LIVE = 'Y' AND "RES_RENT".DESCRIPTION IS NOT NULL

Hello Fateh,
you can union both selects and then get the XML from the subquery.
SELECT  XMLELEMENT(
             "LISTINGS"
            ,XMLAGG(
                 XMLELEMENT(
                     "LISTING"
                    ,XMLFOREST(
                         rr_and_rs.ref_no AS "Property_Ref_No"
                        ,rr_and_rs."UNIT_TYPE" AS "Unit_Type"
                        ,'Sale' AS "Ad_Type"
                        ,'Dubai' AS "State"
                        ,rr_and_rs..location_name_en AS "Community"
                        ,rr_and_rs."PROJECT_NAME_EN" AS "Property_Name"
                        ,rr_and_rs."ASKING_PRICE" AS "Price"
                        ,' ' AS "Frequency"
                        ,rr_and_rs."SUB_TYPE" AS "Unit_Model"
                        ,rr_and_rs."RES_SIZE" AS "Unit_Builtup_Area"
                        ,rr_and_rs.beds AS "Bedrooms"
                        ,rr_and_rs.bath AS "No_of_Bathrooms"
                        ,rr_and_rs."AD_TITLE" AS "Property_Title"
                        ,rr_and_rs.description AS "Web_Remarks"
                        ,TO_CHAR(rr_and_rs."UPDATED_ON",'YYYY-MM-DD HH:MI:SSPM') AS "Last_Updated"
                        ,rr_and_rs.video AS "Web_Tour"
                        ,(  SELECT  XMLAGG(
                                         XMLFOREST(
                                             'http://thevillaproject.com/apex/erp/IMAGES/'||img.id AS "ImageUrl"
                            FROM    images img
                            WHERE   img.res_id = rr_and_rs.res_id
                            ) Images
            ).getClobVal()
INTO    v_xml
FROM    (
    SELECT  'RR-'||r."RES_ID" AS ref_no
           ,"UNIT_TYPE_LOOKUP"."UNIT_TYPE"
           ,"RES_RENT"."ASKING_PRICE" AS price
    FROM    "RES_RENT" "RES_RENT"
            INNER JOIN res r
              ON (r."RES_ID"="RES_RENT"."RES_ID")
            INNER JOIN "UNIT_STATUS_LOOKUP"
              ON (unit_status_lookup.status_id = "RES_RENT"."RES_STATUS")
            INNER JOIN "PROJECTS" "PROJECTS"
              ON ("PROJECTS"."PROJECT_ID"=r."PROJECT_ID")
            INNER JOIN "UNIT_TYPE_LOOKUP" "UNIT_TYPE_LOOKUP"
              ON ("UNIT_TYPE_LOOKUP"."TYPE_ID"=r."RES_TYPE")
            INNER JOIN "RES_SUB_TYPE_LOOKUP" st
              ON (st."SUB_TYPE_ID"=r."SUB_TYPE")
            INNER JOIN complex_lookup cl
              ON (cl.complex_id = "PROJECTS".complex_id)
            INNER JOIN locations l
              ON (l.location_id = cl.location_id)
    WHERE   "RES_RENT".res_status    IN (5,8)
    AND     "RES_RENT".live         = 'Y'
    AND     "RES_RENT".description IS NOT NULL
    UNION ALL
    SELECT  'RS-'||r."RES_ID" AS ref_no
           ,"UNIT_TYPE_LOOKUP"."UNIT_TYPE"
           ,"RES_SALE"."ASKING_PRICE" AS price
    FROM    "RES_SALE" "RES_SALE"
            INNER JOIN res r
              ON (r."RES_ID"="RES_SALE"."RES_ID")
            INNER JOIN "UNIT_STATUS_LOOKUP"
              ON (unit_status_lookup.status_id = "RES_SALE"."RES_STATUS")
            INNER JOIN "PROJECTS" "PROJECTS"
              ON ("PROJECTS"."PROJECT_ID"=r."PROJECT_ID")
            INNER JOIN "UNIT_TYPE_LOOKUP" "UNIT_TYPE_LOOKUP"
              ON ("UNIT_TYPE_LOOKUP"."TYPE_ID"=r."RES_TYPE")
            INNER JOIN "RES_SUB_TYPE_LOOKUP" st
              ON (st."SUB_TYPE_ID"=r."SUB_TYPE")
            INNER JOIN complex_lookup cl
              ON (cl.complex_id = "PROJECTS".complex_id)
            INNER JOIN locations l
              ON (l.location_id = cl.location_id)
    WHERE   "RES_SALE".res_status    IN (5,8)
    AND     "RES_SALE".live         = 'Y'
    AND     "RES_SALE".description IS NOT NULL
    ) rr_and_rsUntested.
When you want to keep two distinct selects (e.g. for easier maintainance), then have a look at INSERTCHILDXML. There you can add elements to an existing XML. http://docs.oracle.com/cd/E11882_01/appdev.112/e23094/xdb04cre.htm#ADXDB4289
Regards
Marcus
BTW: Your mix of cases and case sensitive vs. case insensitive notation makes the code harder to read than necessary
R.bath
R.BEDS
ST."SUB_TYPE"
"RES_SALE"."ASKING_PRICE"Edited by: Marwim on 17.12.2012 13:15

Similar Messages

  • Select extra row without using UNION ALL in pl/sql

    Hi,
    Can anyone tell me how to select extra row without using UNION or UNION ALL in pl/sql. Actually I want to have my o/p of query as partitioned by designation and ordered by salary and than one extra row which will contain the highest salary in a particular salary. My table has first_name,emp_id,designation and salary column. And I wnt the o/p as.
    Mohinish,12212,SI,46000
    Ram,11212,SSI,47000
    Shyam,12133,SI,48000
    Rick,9898,SI,46000
    Rocky,12312,SSI,56000
    Sariq,23948,SI,43000
    Suman,12789,HR,49000
    Sampy,12780,SI,46000
    Parna,11111,HR,50000
    Now the o/p should be.
    Mohinish,12212,SI,46000
    Rick,9898,SI,46000
    Sariq,23948,SI,43000
    Shyam,12133,SI,48000
    Shyam,12133,SI,48000
    Ram,11212,SSI,47000
    Rocky,12312,SSI,56000
    Rocky,12312,SSI,56000
    Suman,12789,HR,49000
    Parna,11111,HR,50000
    Parna,11111,HR,50000
    Thanks in Advance

    You don't have to do a UNION or UNION ALL in PL/SQL but you would need to in SQL to get the desired output:
    with data_recs
    as (select 'Mohinish' first_name,12212 emp_id,'SI' designation,46000 salary from dual union
         select 'Ram',11212,'SSI',47000 from dual union
         select 'Shyam',12133,'SI',48000 from dual union
         select 'Rick',9898,'SI',46000 from dual union
         select 'Rocky',12312,'SSI',56000 from dual union
         select 'Sariq',23948,'SI',43000 from dual union
         select 'Suman',12789,'HR',49000 from dual union
         select 'Sampy',12780,'SI',46000 from dual union
         select 'Parna',11111,'HR',50000 from dual)
    select first_name, emp_id, designation, salary from data_recs union all
    select s.first_name, s.emp_id, s.designation, s.salary
      from (select first_name,
                   emp_id,
                   designation,
                   salary,
                   row_number() over (partition by designation order by salary desc) high_salary
              from data_recs
             order by designation, salary) s
    where s.high_salary = 1
    order by designation, salary;
    FIRST_NAME  EMP_ID DESIGNATION   SALARY
    Suman        12789 HR             49000
    Parna        11111 HR             50000
    Parna        11111 HR             50000
    Sariq        23948 SI             43000
    Rick          9898 SI             46000
    Mohinish     12212 SI             46000
    Sampy        12780 SI             46000
    Shyam        12133 SI             48000
    Shyam        12133 SI             48000
    Ram          11212 SSI            47000
    Rocky        12312 SSI            56000
    Rocky        12312 SSI            56000

  • Sql query using union

    hi
    i need the query to fetch the data ...
    i have two table
    1. plan
    2. voidplan
    each table has id uniquely, and each table has rep_id but it is not unique.
    i retrieved the data from both table using union. now i need the data for the rep who is in both table. i want to check union by id, and i need to retrieve the reps who is in both tables.
    my code is
    select "PLAN"."ID" as "ID",
         "PLAN"."REP_ID" as "REP_ID",
         "PLAN"."REGION" as "REGION",
         "PLAN"."LOB" as "LOB",
         "PLAN"."PLAN_HIERARCHY_CHANGE" as "PLAN_HIERARCHY_CHANGE"
    from     "PLAN" "PLAN" ,"VOIDPLAN" "VOIDPLAN" where "PLAN"."REP_ID" IN (SELECT REP_ID FROM VOIDPLAN)
    UNION
    SELECT "VOIDPLAN"."ID" as "ID",
         "VOIDPLAN"."REP_ID" as "REP_ID",
         "VOIDPLAN"."REGION" as "REGION",
         "VOIDPLAN"."LOB" as "LOB",
         "VOIDPLAN"."PLAN_HIERARCHY_CHANGE" as "PLAN_HIERARCHY_CHANGE"
    from     "VOIDPLAN" "VOIDPLAN"
    THIS QUERY GIVES ALL UNION RESULT, NUT IT DOES'T FILTER THE REP_ID, IT SHOWS ALL THE REP_ID, I NEED THE REPS WHO IS IN BOTH TABLES
    CAN ANYONE PLEASE TELL ME THE SOLUTION
    regards
    vally.s

    SQL> create table plan
      2  as
      3  select 1 id, 1111 rep_id, 'vally' rep_name from dual union all
      4  select 2, 2222, 'kavi' from dual union all
      5  select 3, 3333, 'shyam' from dual
      6  /
    Tabel is aangemaakt.
    SQL> create table voidplan
      2  as
      3  select 5 id, 1111 rep_id, 'vally' rep_name from dual union all
      4  select 6, 2222, 'kavi' from dual
      5  /
    Tabel is aangemaakt.
    SQL> select case x when 1 then p.id else v.id end id
      2       , p.rep_id
      3       , p.rep_name
      4    from plan p
      5       , voidplan v
      6       , (select 1 x from dual union select 2 from dual) x
      7   where p.rep_id = v.rep_id
      8   order by 1
      9  /
       ID REP_ID REP_N
        1   1111 vally
        2   2222 kavi
        5   1111 vally
        6   2222 kavi
    4 rijen zijn geselecteerd.Regards,
    Rob.

  • Need sql query to remove duplicates using UNION ALL clause

    Hi,
    I have a sql query which has UNION clause.But the UNION clause is causing some performance issues.
    To overcome that I have used UNION ALL to improve performance but its returning duplicates.
    Kindly anyone send a sample SQL query where my primary objective is used to use UNION ALL clause and to consider unique rows (elimating duplicate
    ones)
    Any help will be needful for me
    Thanks and Regards

    why not UNION? :(
    another way also use MINUS
    SQL>
    SQL> with t as
      2  (
      3  select 1 if from dual union all
      4  select 2 if from dual union all
      5  select 1 if from dual union all
      6  select 3 if from dual union all
      7  select 3 if from dual
      8  )
      9  ,t2 as
    10  (
    11  select 1 if from dual union all
    12  select 2 if from dual union all
    13  select 3 if from dual union all
    14  select 4 if from dual union all
    15  select 5 if from dual
    16  )
    17  (select if from t
    18  union all
    19  select if from t2)
    20  /
            IF
             1
             2
             1
             3
             3
             1
             2
             3
             4
             5
    10 rows selected
    SQL> so
    SQL>
    SQL> with t as
      2  (
      3  select 1 if from dual union all
      4  select 2 if from dual union all
      5  select 1 if from dual union all
      6  select 3 if from dual union all
      7  select 3 if from dual
      8  )
      9  ,t2 as
    10  (
    11  select 1 if from dual union all
    12  select 2 if from dual union all
    13  select 3 if from dual union all
    14  select 4 if from dual union all
    15  select 5 if from dual
    16  )
    17  (select if from t
    18  union all
    19  select if from t2)
    20  minus
    21  select -99 from dual
    22  /
            IF
             1
             2
             3
             4
             5
    SQL>

  • SQL query error using Union

    Hello!
    I need some correction in the following query. I am trying to make a 2 page QPLD so I am joining 2 queries and then printing the report into 2 pages.
    SELECT T0.[U_OANumber], T0.[custmrName], T0.[U_Inspection], T0.[U_Cust_PO_Num],
    T0.[U_ModelType], T0.[U_Duty], T0.[U_NamePlate],
    T0.[U_Indicator_Obs], T0.[U_Fastners], T0.[U_Mounting_Type], T0.[U_Casing_Orientation], T0.[U_Impeller_Dia],
    T0.[U_Bearing_Style], T0.[U_Motor_HP_Size], T0.[U_InsulationWedges], T0.[U_Varnish], T0.[U_Paint_Shade],
    T0.[U_PlugsSeal], T0.[U_Remarks], T0.[U_Despatch]
    FROM OINS T0 WHERE T0.[U_OANumber] = '[%0]' or  T0.[customer] = '[%1]' or T0.[manufSN] = '[%2]'
    Union all
    SELECT T0.[U_ModelType], T0.[U_Size], T0.[U_Discharge], T0.[U_Head], T0.[U_RPM], T0.[U_YOM], T0.[U_HP],
    T0.[U_Amps], T0.[U_Insulation_Class], T0.[U_Winding_Connection]
    FROM OINS T0 WHERE
    T0.[U_OANumber] = '[%0]' or  T0.[customer] = '[%1]' or T0.[manufSN] = '[%2]'
    Do I have to use the where clause just once since it is identical to both statements?
    I get the error stating that all queries using Union, Intersect or Except must have an equal number of expressions. what does this mean?
    scorp
    Edited by: scorpion 666 on Feb 12, 2009 1:30 PM

    Union has to have exact same numbers of fields to combine two results.  Your query shows no need of union because your where clauses are identical.
    Right syntax would be like this:
    SELECT T0.[U_OANumber], T0.[custmrName], T0.[U_Inspection], T0.[U_Cust_PO_Num],
    T0.[U_ModelType], T0.[U_Duty], T0.[U_NamePlate],
    T0.[U_Indicator_Obs], T0.[U_Fastners], T0.[U_Mounting_Type], T0.[U_Casing_Orientation], T0.[U_Impeller_Dia],
    T0.[U_Bearing_Style], T0.[U_Motor_HP_Size], T0.[U_InsulationWedges], T0.[U_Varnish], T0.[U_Paint_Shade],
    T0.[U_PlugsSeal], T0.[U_Remarks], T0.[U_Despatch], T0.[U_Size], T0.[U_Discharge], T0.[U_Head], T0.[U_RPM], T0.[U_YOM], T0.[U_HP],
    T0.[U_Amps], T0.[U_Insulation_Class], T0.[U_Winding_Connection]
    FROM DBO.OINS T0 WHERE T0.[U_OANumber] = '[%0]' or  T0.[customer] = '[%1]' or T0.[manufSN] = '[%2]'
    Thanks,
    Gordon

  • SQL - JOIN using UNION ?? UNION using JOIN ?? with example!

    I was asked this question during one of my interviews. Can you do JOIN using UNION keyword? Can you do UNION using JOIN keyword?
    That is -
    1. I should get same output as JOIN without using JOIN keyword, but using UNION Keyword?
    2. I should get same output as UNION without using UNION keyword, but using JOIN Keyword?
    Can you give me an example of how to do this if possible?

    Hi,
    Welcome to the forum!
    user13067794 wrote:
    I was asked this question during one of my interviews. Can you do JOIN using UNION keyword? Can you do UNION using JOIN keyword?The correct answer to those questions is: Why would you want to? All versions of Oracle (and probably any other database product) provide JOIN to do certain things and UNION to do other things. Why not use those features the way they were designed to be used? Even if it is possible to do what you ask, it's going to be more complicated and less efficient.
    If you really must:
    That is -
    1. I should get same output as JOIN without using JOIN keyword, but using UNION Keyword? You can select the relevant columns from each table, and NULLs for all the columns from other tables, in a UNION query. Then you can use GROUP BY or analytic functions to combine data from different rows. For example, this JOIN:
    SELECT     d.dname
    ,     e.mgr
    FROM     scott.dept     d
    JOIN     scott.emp     e  ON     d.deptno  = e.deptno
    ;could be written using UNION, but no JOIN, like this:
    WITH     union_data     AS
         SELECT     deptno
         ,     dname
         ,     NULL     AS empno
         ,     NULL     AS mgr
         FROM     scott.dept
        UNION ALL
         SELECT     deptno
         ,     NULL     AS dname
         ,     empno
         ,     mgr
         FROM     scott.emp
    ,     quasi_join     AS
         SELECT     MAX (dname) OVER (PARTITION BY deptno)     AS dname
         ,     mgr
         ,     empno
         FROM     union_data
    SELECT     dname
    ,     mgr
    FROM     quasi_join
    WHERE     empno     IS NOT NULL
    ;Depending on your tables and your requirements, you might be able to do something a little simpler.
    2. I should get same output as UNION without using UNION keyword, but using JOIN Keyword?A FULL OUTER JOIN is similar to UNION.
    This UNION query:
    SELECT     dname          AS txt
    FROM     scott.dept
    UNION
    SELECT     TO_CHAR (mgr)     AS txt
    FROM     scott.emp
    ;Can be written like this, using JOIN but no UNION:
    SELECT DISTINCT
         NVL2 ( e.empno
              , TO_CHAR (e.mgr)
              , d.dname
              )          AS txt
    FROM          scott.dept     d
    FULL OUTER JOIN     scott.emp     e  ON       1 = 2
    user13067794 wrote:I too don't any example as such, but I am thinking on this line -
    Select a.x, b.y
    from a,b
    where a.key=b.key and sal<5000
    UNION
    Select a.x, b.y
    From a,b
    Where a.key=b.key and sal>7000
    can we get same result using JOIN?That's a very special case. You can get the same results without using UNION like this:
    Select distinct
         a.x
    ,      b.y
    from      a
    ,     b
    where      a.key     = b.key
    and      (        sal < 5000
         OR     sal > 7000
    Can we do something similar using UNION without using JOIN keyword??What you posted does not use the JOIN keyword.
    To get the same results without using a join (either with or without the JOIN keyword), you can use UNION together with aggregate or analytic functions, as I showed earlier.
    Edited by: Frank Kulash on Jul 5, 2011 9:01 PM

  • Query takes long when using UNION

    Hi ,
    I habe a query as follows;
    SELECT
                        '9999' site_id,
                        m.ghi_prov_num provnum,
                           SUBSTR (l.seq_num, 1, 3)provloc,
                        t.dea_number dea,
                            t.license_number statelicensenumber ,
                            n.npi_num npi,
                            m.prefix prefixname,
                            m.lastname lastname,
                            m.firstname firstname,
                            t.middle_name middleinitial,
                            m.suffix suffixname,
                            null clinicname,
                            l.street1 addressline1,
                            l.street2 addressline2,
                            l.city city,
                            l.state state,
                            l.zip5 zip,
                            l.phone phoneprimary,
                            null ext,
                            null fax,
                            null email,
                            null alt_phone,
                            null alt_phone_ext
                     FROM provider m, LOCATION l, npi n,TEMP_VITAL_CACTUS t,test_provider_pin pin
                      WHERE m.ghi_prov_num=l.ghi_prov_num
                          and m.ghi_prov_num=n.ghi_prov_num(+)
                          and m.ghi_prov_num=t.ghi_prov_num(+)
                          and m.tax_id=pin.tax_id
         UNION
          SELECT   
                        '9999', m.ghi_prov_num ,
                            m.location provloc,
                           null  ,
                           null  ,
                            n.npi_num  ,
                            null ,
                            m.lastname ,
                            m.firstname  ,
                            null,
                            null  ,
                            null  ,
                            m.street1  ,
                            m.street2  ,
                            m.city ,
                            m.state  ,
                            m.zip5 ,
                            m.phone  ,
                            null  ,
                            null  ,
                            null  ,
                            null  ,
                            null
                           FROM dental_provider m, npi n,test_provider_pin pin
                       WHERE m.ghi_prov_num=n.tax_id(+)
                           and m.location=n.location(+)
                            and pin.tax_id=m.ghi_prov_num;The query takes for ever;
    But Individual query takes less than a sec to execute.Is there any way can i rewrite the query?
    Please help
    Hena.

    user11253970 wrote:
    But Individual query takes less than a sec to execute.Is there any way can i rewrite the query?Have a feeling you are using Toad/SQL Navigator or similar tool which returns data one screen at a time. If so, then it does not "takes less than a sec to execute" but rather to fetch first screen of rows. When you use UNION Oracle has to return distinct rows from both queries. Therefore it must fetch not just first screen but all rows. To verify, issue first query and in yiour GUI tool click on get last screen. Then you'll know how long whole select takes. Do the same for second query. Also, do you need distinct rows or akll rows? IF all rows, change UNION to UNION ALL.
    SY.

  • How to use union statement with declare & set function?

    Hi Experts,
            i  have small query about how to use union statement with declare & set function?
    Example as below :
    DECLARE @name AS date
    Declare @name2  AS date
    /* SELECT FROM [2013].[dbo].[OINV] T0 */
    /* WHERE */
    SET @name = /* T0.DocDate */ '[%1]'
    SET @name2 = /* T0.DocDate */ '[%2]'
    select  '2013',t5.U_salmannm,t1.CardName,t2.sumapplied as CollectionAmount,t2.DcntSum ,t3.DocTotal as InvoiceTotal,
    datediff(dd,t3.DocDate,t1.Docdate) as Days
    from 2013.dbo.orct t1
    inner join 2013.dbo.RCT2 t2 on t1.DocNum = t2.DocNum
    left join 2013.dbo.oinv t3 on
    t3.docentry = t2.baseAbs
    inner join 2013.dbo.ocrd t4 on t1.Cardcode = t4.CardCode
    inner join [2013].[dbo].[@CQ_RTSM] t5 on t4.U_BeatCode = t5.U_RoutCode
    where t2.DcntSum <> 0.000000 and t3.DocDate between [%1] and [%2]
    Union
    /* SELECT FROM [2014].[dbo].[OINV] T0 */
    /* WHERE */
    SET @name = /* T0.DocDate */ '[%1]'
    SET @name2 = /* T0.DocDate */ '[%2]'
    select  '2014',t5.U_salmannm,t1.CardName,t2.sumapplied as CollectionAmount,t2.DcntSum ,t3.DocTotal as InvoiceTotal,
    datediff(dd,t3.DocDate,t1.Docdate) as Days
    from 2014.dbo.orct t1
    inner join 2014.dbo.RCT2 t2 on t1.DocNum = t2.DocNum
    left join 2014.dbo.oinv t3 on
    t3.docentry = t2.baseAbs
    inner join 2014.dbo.ocrd t4 on t1.Cardcode = t4.CardCode
    inner join [2014].[dbo].[@CQ_RTSM] t5 on t4.U_BeatCode = t5.U_RoutCode
    where t2.DcntSum <> 0.000000 and t3.DocDate between [%1] and [%2]

    You have to create stored procedure in SQL only .
    Like u must have create for Crystal .
    You can execute procedure in query manager but you have to enter parameter manually..
    example
    Exec @Test '20140101' '20140501'
    Every time user has to enter it manually in yyyymmdd format in case of date parameters.
    Example
    Create Proc [@Test]
    as begin
    DECLARE @name AS date
    Declare @name2  AS date
    /* SELECT FROM [2013].[dbo].[OINV] T0 */
    /* WHERE */
    select  '2013',t5.U_salmannm,t1.CardName,t2.sumapplied as CollectionAmount,t2.DcntSum ,t3.DocTotal as InvoiceTotal,
    datediff(dd,t3.DocDate,t1.Docdate) as Days
    from 2013.dbo.orct t1
    inner join 2013.dbo.RCT2 t2 on t1.DocNum = t2.DocNum
    left join 2013.dbo.oinv t3 on
    t3.docentry = t2.baseAbs
    inner join 2013.dbo.ocrd t4 on t1.Cardcode = t4.CardCode
    inner join [2013].[dbo].[@CQ_RTSM] t5 on t4.U_BeatCode = t5.U_RoutCode
    where t2.DcntSum <> 0.000000 and t3.DocDate between @Name and @Name2
    Union
    /* SELECT FROM [2014].[dbo].[OINV] T0 */
    /* WHERE */
    select  '2014',t5.U_salmannm,t1.CardName,t2.sumapplied as CollectionAmount,t2.DcntSum ,t3.DocTotal as InvoiceTotal,
    datediff(dd,t3.DocDate,t1.Docdate) as Days
    from 2014.dbo.orct t1
    inner join 2014.dbo.RCT2 t2 on t1.DocNum = t2.DocNum
    left join 2014.dbo.oinv t3 on
    t3.docentry = t2.baseAbs
    inner join 2014.dbo.ocrd t4 on t1.Cardcode = t4.CardCode
    inner join [2014].[dbo].[@CQ_RTSM] t5 on t4.U_BeatCode = t5.U_RoutCode
    where t2.DcntSum <> 0.000000 and t3.DocDate between
    between @Name and @Name2
    end

  • Join two tables using union

    Hi Gurus,
    I have three tables. I want to join all tables using union in SQL statement. The query is returning all the records from both tables but i only require unique rows based on a specific column value. Here is my table structure -
    TableA -
    LIC_ID          NUMBER(10)     NOT NULL
    LIC_NUMBER     VARCHAR2(20)
    COMMENCE_DATE     DATE
    EXPIRY_DATE     DATE
    TERM          VARCHAR2(20)LIC_ID is the primary key in this table -
    Sample data from TableA
    LIC_ID          LIC_NUMBER     COMMENCE_DATE          EXPIRY_DATE     TERM
    2          TR4323          12/04/2008          11/03/2010     2 Years
    34          TR5432          23/07/2009          22/07/2010     1 Year
    45          TR5321          24/06/2009          23/06/2010     1 Year
    65          TR6666          23/07/2010          22/07/2011     1 Year
    32          TR2423          30/05/2010          29/05/2011     1 YearTableB -
    MAR_ID          NUMBER(10)     NOT NULL
    LIC_ID          NUMBER(10)     NOT NULL
    ZONE_NAME     VARCHAR2(20)
    DEPARTMENT     VARCHAR2(20)
    ACTIVITIES     VARCHAR2(200)
    COMMENTS     VARCHAR2(200)MAR_ID is the primary key in this table and LIC_ID is the foreign key on TableA
    Sample data from TableB -
    MAR_ID          LIC_ID          ZONE_NAME     DEPARTMENT     ACTIVITIES     COMMENTS
    23          2          ZONE A          IT          NONE               
    43          34          ZONE B          IT          NONE
    33          65          ZONE C          ACCOUNT          NONE     
              TableC
    REC_ID          NUMBER(10)     NOT NULL
    LIC_ID          NUMBER(10)     NOT NULL
    DIST_NAME     VARCHAR2(20)
    REGION          VARCHAR2(20)
    ACTIVITIES     VARCHAR2(200)
    COMMENTS     VARCHAR2(200)REC_ID is the primary key in this table and LIC_ID is the foreign key.
    Sample data -
    REC_ID          LIC_ID          DIST_NAME     REGION          ACTIVITIES     COMMENTS
    2          45          SA          NORTH          NONE
    3          65          TA          NORTH          NONE
    5          32          NT          SOUTH          NONEHere is my sql query -
    select a.lic_id, a.lic_number, a.commence_date, a.expiry_date from
    TableA a, TableB b
    where a.lic_id=b.lic_id
    union
    select a.lic_id, a.lic_number, a.commence_date, a.expiry_date from
    TableA a, TableC c
    where a.lic_id=c.lic_idThe above query returns -
    lic_id          lic_number     commence_date          expiry_date          
    2          TR4323          12/04/2008          11/03/2010     
    34          TR5432          23/07/2009          22/07/2010     
    45          TR5321          24/06/2009          23/06/2010     
    65          TR6666          23/07/2010          22/07/2011     
    32          TR2423          30/05/2010          29/05/2011
    65          TR6666          23/07/2010          22/07/2011     LIC_ID 65 exists in both table TableB and TableC hence it repeats in query but I want to display that only once. How can I do that? I want to return unique record on LIC_NUMBER.
    Hope this make sence.
    Many thanks,
    Tajuddin

    Thanks for all your reply and suggestions. David altering session did not work.
    Sven your idea helped me to figure it out what to do. I found a way around to fix it. Here is my current code -
    select a.lic_id, a.lic_number, a.commence_date, a.expiry_date from
    TableA a, TableB b
    where a.lic_id=b.lic_id
    union
    select a.lic_id, a.lic_number, a.commence_date, a.expiry_date from
    TableA a, TableC c
    where a.lic_id=c.lic_id and c.lic_id not in ( select lic_id from TableB)This will exclude any LIC_ID exists in TableB.
    Thanks again for your help guys.
    Regards,
    M Tajuddin
    Web: http://tajuddin.whitepagesbd.com
    Blog: http://aspblog.whitepagesbd.com

  • Writing query using UNION Operator

    Question -
    (1)
    Write an SQL Statement to list the following items: Customer ID, Customer Name, number of invoices, sum of total for invoices. Ensure that all customers are returned in the result set.
    Answer for the above is written as below by one person. That seams to be correct. Is there another way of writing this same query.;
    select c.CUSTOMER_ID,c.NAME,i.cnt,i.s
    from gee_customer c,(select customer_id,count(*) as cnt, sum(TOTAL) as s
    from gee_invoice
    group by customer_id) i
    where c.CUSTOMER_ID = i.customer_id (+)
    (2)
    My other question is How to write the above answer (or what you sugest) using UNION operator ?
    Any ideas please
    Message was edited by:
    user483578

    In fact the outer join means you use the union of two result sets - usual join result
    and the rows from the outer table for which there is not any row in the inner table.
    SQL> select d.deptno, e.ename from emp e, dept d
      2  where d.deptno = e.deptno(+)
      3  order by 1,2
      4  /
        DEPTNO ENAME
            10 CLARK
            10 KING
            10 MILLER
            20 ADAMS
            20 FORD
            20 JONES
            20 SCOTT
            20 SMITH
            30 ALLEN
            30 BLAKE
            30 JAMES
            30 MARTIN
            30 TURNER
            30 WARD
            40
    15 rows selected.
    SQL> select d.deptno,e.ename from emp e, dept d
      2  where d.deptno = e.deptno
      3  union
      4  select deptno, null
      5  from dept d where not exists (select null from emp e where e.deptno = d.deptno)
      6  order by 1,2
      7  /
        DEPTNO ENAME
            10 CLARK
            10 KING
            10 MILLER
            20 ADAMS
            20 FORD
            20 JONES
            20 SCOTT
            20 SMITH
            30 ALLEN
            30 BLAKE
            30 JAMES
            30 MARTIN
            30 TURNER
            30 WARD
            40
    15 rows selected.In your example something like (NOT tested !)
    with i as (select customer_id,count(*) as cnt, sum(TOTAL) as s
    from gee_invoice group by customer_id)
    select c.CUSTOMER_ID,c.NAME,i.cnt,i.s
    from gee_customer c, i
    where c.CUSTOMER_ID = i.customer_id
    union
    select c.CUSTOMER_ID,c.NAME,null,null
    from gee_customer c
    where not exists (select null from i where c.CUSTOMER_ID = i.customer_id)
    Rgds.

  • Using Union in popup LOV

    HI,
    I want to select data from 2 tables using Union in Popup LOV ,
    please help.
    I am getting a error message like
    "LOV query is invalid, a display and a return value are needed, the column names need to be different. If your query contains an in-line query, the first FROM clause in the SQL statement must not belong to the in-line query."
    when i use union query
    my query is like this
    select a from table 1
    union
    select b from table 2
    order by a;

    Hi,
    Three things -
    1) Remove the semi-colon from the end of your query (it can work without it, but you'll eventually run into problems some day by putting a semi-colon on the end, so better to get into the habit of not doing it).
    2) You need to provide 2 columns in your query, a display value and a return value (look at the error message you are getting). You are only returning a single column.
    3) Wrap your query inside another query to get it to work.
    Something like this should work -
    select * from (
      select 1 as r, 2 as d from dual
      union
      select 3 as r, 4 as d from dual)
    order by dObviously change the values/columns to suit your own purposes.
    Hope this helps,
    John.

  • Cannot export query output when using UNION ALL

    Hi
    I can run a query in SQL Developer 1.5.5 and if it's a SELECT statement it works fine, but if I output the result of several SELECT statements using UNION ALL after some 10,000 records the SQL Developer crashes and it generates a file whose size is 0 kb
    Is there a workaround for this??
    Thanks and Regards!
    Isaac

    Should be fixed in the upcoming 2.1... you can try the RC1 also...
    Regards,
    K.

  • Creating table or View using UNION Operator ???????

    Hi all
    please need some help ,i have created aquery using UNION operator
    (i.e
    select A,to_number(null),C from table1
    Union
    select A,B,To_number(null) from table2)
    it gives the output correctly and i need to make this output as View ot table
    eacg time i use
    Create or replace view v_1 ...........
    it gives me this error :: unknown command "UNION" - rest of line ignored.
    can any one pls tell me what to do
    Thanks

    Hi,
    I found there is no error in your sql
    create view x_v
    as
    select a from x
    union
    select to_number(null) from y;
    this works fine.
    in your sql check your right or left peranthesis
    regards
    Ripudaman

  • Performance using UNION ALL

    Hello
    i have 2 schemas S1 and S2 containing complex relational tables. The tables in each schema are related to each other via foreign key relationships. i made views for feature tables in both the schemas , querying column values from their related tables.
    the data structure in both the schemas are exactly the same. Dut to management reasons we have to split them in 2 schemas. S1 contain data for region A and S2 contains data from region B. Now the client wants to see a combined data from region A & B.
    we are planning to create another schema S3 and make views combining views from S1 and S2 in both schemas (V1 in S1 + V1 in S2) using UNION ALL.
    Does UNION ALL will make use of the indexes we already built for parent tables in S1 and S2? Will there be a performance degradation using this approach? What can be the best approach? Our client needs to see real time data....
    regards
    sam

    Since union does an extra sort it has a performance difference compared to union all.
    SQL> select user from dual union select user from dual ;
    USER
    HR
    SQL> select user from dual union all select user from dual ;
    USER
    HR
    HRİf there is up to date and appropriate object statistics Oracle's Cost Based Optimizer will choose best access path, join method and join order depending on your query. Only exceptions are hints, outlines and sql profiles since they stabilize the execution plan.
    For further commenting please post your oracle version, query's test results and its statistics taken from sql*plus timing and autotrace options - http://www.bhatipoglu.com/entry/17/oracle-performance-analysis-tracing-and-performance-evaluation

  • Performance using union

    I am using union of around 6 queries in a report. The same query in the database runs faster where as the report takes long time. Please suggest what can be done.
    thanks,
    deep

    Since union does an extra sort it has a performance difference compared to union all.
    SQL> select user from dual union select user from dual ;
    USER
    HR
    SQL> select user from dual union all select user from dual ;
    USER
    HR
    HRİf there is up to date and appropriate object statistics Oracle's Cost Based Optimizer will choose best access path, join method and join order depending on your query. Only exceptions are hints, outlines and sql profiles since they stabilize the execution plan.
    For further commenting please post your oracle version, query's test results and its statistics taken from sql*plus timing and autotrace options - http://www.bhatipoglu.com/entry/17/oracle-performance-analysis-tracing-and-performance-evaluation

Maybe you are looking for

  • Can I create a LaunchDaemon for my 3rd-party wireless card?

    Hi there, I wanted to get .11n wireless on my old Power Mac G5 (Quad 2.5) so I bought a third-party PCI-E card. It works fine, however it's not AirPort compatible, and so at present I have to run it from my Login Items, which in turn means the networ

  • Ipod Occasionally Freezes When Turned On

    I'm wondering if problems I am having are being caused by the "1.2 firmware freezing problem." I got my 5th gen video Ipod after Itunes 7 was released, so I never had an earlier firmware on my ipod. My ipod does not freeze while playing music, but it

  • How to create a service to UPLOAD / DOWNLOAD and send emails with files?

    Good afternoon! I need to create a service that sends files via email or FTP, and a service to upload / download files on a server. I see on the internet does not have much aid to make it in the ADF. Could someone send me some links, documentation, s

  • XI 3.0  Sender Agreement error during Configuration Wizard

    Hi During the Sender Agreement generation of the Configuration Wizard an error occurs because it takes the value of "" for Receiver Party and Service.  This was discuused during the XI252 Session at the San Diego SAP TechEd.  The proposed solution wa

  • KDE 4.6 Oxygen corruption with i965 driver

    Does anyone suffer from graphics corruption when using oxygen with intel drivers ? Here is the screenshot: This is only a problem when using oxygen window decorations, with dekorator there are no problems of this sort. I can't be sure if this is oxyg