Combining the results of 2 SQL blocks

Hi
I have 2 SQL statement blocks:-
SELECT
D.DEPARTMENT_NAME "Department",
COUNT(E.EMPLOYEE_ID) "No. Of Employees",
MIN(SALARY)"Minimum Salary",
MAX(SALARY)"Maximum Salary",
SUM(SALARY)"Total Salary"
FROM EMPLOYEES E
JOIN DEPARTMENTS D USING (DEPARTMENT_ID)
GROUP BY D.DEPARTMENT_NAME
ORDER BY SUM(SALARY) ASC
and
SELECT
D.DEPARTMENT_NAME,
C.COUNTRY_NAME
FROM DEPARTMENTS D
JOIN LOCATIONS L USING (LOCATION_ID)
JOIN COUNTRIES C USING (COUNTRY_ID)
My problem is that I want to include the department and location (country name) for each of the departments being returned in my cobmined result set. The 1st block gets me most of the information I need. The 2nd block gets me the the department name and the country in which it's located. I've tried having the 2nd block as a sub query but can't because it's not a single-row query. Any ideas?
Thanks.

try
SELECT D.DEPARTMENT_NAME "Department",
C.COUNTRY_NAME,
COUNT(E.EMPLOYEE_ID) "No. Of Employees",
MIN(SALARY)"Minimum Salary",
MAX(SALARY)"Maximum Salary",
SUM(SALARY)"Total Salary"
FROM EMPLOYEES E
JOIN DEPARTMENTS D USING (DEPARTMENT_ID)
JOIN LOCATIONS L USING (LOCATION_ID)
JOIN COUNTRIES C USING (COUNTRY_ID)
GROUP BY D.DEPARTMENT_NAME, C.COUNTRY_NAME
ORDER BY SUM(SALARY) ASC

Similar Messages

  • How to export the result from executing sql statement to excel file ?

    HI all,
    Great with Oracle SQL Developer, but I have have a trouble as follwing :
    I want to export the result from executing sql statement to excel file . I do easily like that in TOAD ,
    anyone can help me to do that ? Thanks so much
    Sigmasvn

    Hello Sue,
    I just tried to export to excel with the esdev extension and got java.lang.NumberFormatException. I found the workaround at Re: Windows Multi-language env, - how do I set English for application lang?
    open the file sqldeveloper\jdev\bin\sqldeveloper.conf and add the following two lines:
    AddVMOption -Duser.language=en
    AddVMOption -Duser.country=USyet now my date formats in excel are 'american-style' instead of german. For example 01-DEC-01 so excel does not recognize it as date and therefore I can not simply change the format.
    When export to excel will be native to 1.1 perhaps someone can have a look at this 'feature'
    Regards
    Marcus

  • End the result of an sql query by Email as an excel file attachement

    Hi,
    I would like to create a PL/SQL function that send the result of an sql query by Email as an excel file attachement.
    i'm newbie in pl/sql an d i dont know if it's possible to do such task.
    regards,

    i think a regular expression is he way to go in your case...
    Azadi Saryev
    Sabai-dee.com
    http://www.sabai-dee.com

  • Pass the result of a SQL Query as table_name  for another SQL Query

    Hi All,
    How to pass the result of a SQL Query as parameter to another SQL Query
    Eg: I am doing the steps below.
    1) select distinct table_name as TAB1 from all_tab_cols where table_name like 'T_%' and column_name like '%XYZ'
    2) I want to pass the table_name from step 1 above as parameter to another query "select * from TAB1"
    Thanks

    Naveen B wrote:
    Hi All,
    How to pass the result of a SQL Query as parameter to another SQL Query
    Eg: I am doing the steps below.
    1) select distinct table_name as TAB1 from all_tab_cols where table_name like 'T_%' and column_name like '%XYZ'
    2) I want to pass the table_name from step 1 above as parameter to another query "select * from TAB1"
    ThanksYou should craete PL/SQL code with cursor which will accept a parameter and call that cursor inside the first one
    But if the first sql returns only one row, you can do it with simple sql code
    select * from (select distinct table_name as TAB1 from all_tab_cols where table_name like 'T_%' and column_name like '%XYZ')- - - - - - - - - - - - - - - - - - - - -
    Kamran Agayev A. (10g OCP)
    http://kamranagayev.wordpress.com
    [Step by Step install Oracle on Linux and Automate the installation using Shell Script |http://kamranagayev.wordpress.com/2009/05/01/step-by-step-installing-oracle-database-10g-release-2-on-linux-centos-and-automate-the-installation-using-linux-shell-script/]

  • Bind Variable in SELECT statement and get the value  in PL/SQL block

    Hi All,
    I would like  pass bind variable in SELECT statement and get the value of the column in Dynamic SQL
    Please seee below
    I want to get the below value
    Expected result:
    select  distinct empno ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    100, HR
    select  distinct ename ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    TEST, HR
    select  distinct loc ,pr.dept   from emp pr, dept ps where   ps.dept like '%IT'  and pr.empno =100
    NYC, HR
    Using the below block I am getting column names only not the value of the column. I need to pass that value(TEST,NYC..) into l_col_val variable
    Please suggest
    ----- TABLE LIST
    CREATE TABLE EMP(
    EMPNO NUMBER,
    ENAME VARCHAR2(255),
    DEPT VARCHAR2(255),
    LOC    VARCHAR2(255)
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (100,'TEST','HR','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (200,'TEST1','IT','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (300,'TEST2','MR','NYC');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (400,'TEST3','HR','DTR');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (500,'TEST4','HR','DAL');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (600,'TEST5','IT','ATL');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (700,'TEST6','IT','BOS');
    INSERT INTO EMP (EMPNO,ENAME,DEPT,LOC) VALUES (800,'TEST7','HR','NYC');
    COMMIT;
    CREATE TABLE COLUMNAMES(
    COLUMNAME VARCHAR2(255)
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('EMPNO');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('ENAME');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('DEPT');
    INSERT INTO COLUMNAMES(COLUMNAME) VALUES ('LOC');
    COMMIT;
    CREATE TABLE DEPT(
    DEPT VARCHAR2(255),
    DNAME VARCHAR2(255)
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('IT','INFORMATION TECH');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('HR','HUMAN RESOURCE');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('MR','MARKETING');
    INSERT INTO DEPT(DEPT,DNAME) VALUES ('IT','INFORMATION TECH');
    COMMIT;
    PL/SQL BLOCK
    DECLARE
      TYPE EMPCurTyp  IS REF CURSOR;
      v_EMP_cursor    EMPCurTyp;
      l_col_val           EMP.ENAME%type;
      l_ENAME_val       EMP.ENAME%type;
    l_col_ddl varchar2(4000);
    l_col_name varchar2(60);
    l_tab_name varchar2(60);
    l_empno number ;
    b_l_col_name VARCHAR2(255);
    b_l_empno NUMBER;
    begin
    for rec00 in (
    select EMPNO aa from  EMP
    loop
    l_empno := rec00.aa;
    for rec in (select COLUMNAME as column_name  from  columnames
    loop
    l_col_name := rec.column_name;
    begin
      l_col_val :=null;
       l_col_ddl := 'select  distinct :b_l_col_name ,pr.dept ' ||'  from emp pr, dept ps where   ps.dept like ''%IT'' '||' and pr.empno =:b_l_empno';
       dbms_output.put_line('DDL ...'||l_col_ddl);
       OPEN v_EMP_cursor FOR l_col_ddl USING l_col_name, l_empno;
    LOOP
        l_col_val :=null;
        FETCH v_EMP_cursor INTO l_col_val,l_ename_val;
        EXIT WHEN v_EMP_cursor%NOTFOUND;
          dbms_output.put_line('l_col_name='||l_col_name ||'  empno ='||l_empno);
       END LOOP;
    CLOSE v_EMP_cursor;
    END;
    END LOOP;
    END LOOP;
    END;

    user1758353 wrote:
    Thanks Billy, Would you be able to suggest any other faster method to load the data into table. Thanks,
    As Mark responded - it all depends on the actual data to load, structure and source/origin. On my busiest database, I am loading on average 30,000 rows every second from data in external files.
    However, the data structures are just that - structured. Logical.
    Having a data structure with 100's of fields (columns in a SQL table), raise all kinds of questions about how sane that structure is, and what impact it will have on a physical data model implementation.
    There is a gross misunderstanding by many when it comes to performance and scalability. The prime factor that determines performance is not how well you code, what tools/language you use, the h/w your c ode runs on, or anything like that. The prime factor that determines perform is the design of the data model - as it determines the complexity/ease to use the data model, and the amount of I/O (the slowest of all db operations) needed to effectively use the data model.

  • Use the results of an SQL query to create another query

    I am working on a bidding/allocation system using C# and MySQL, and I am currently having difficulty implementing the “post-allocation” mechanics of the system. Let me explain how it works, before introducing the code:
    When the bids are made on the system, they all have the position 0, so the first thing the system does is order them according to priority.
     (bid table)
    In this case, 5 bidders are interested in what is in plot 15, but we have not assigned them a position yet.
     (bid table)
    The system then organises the bids according to the order in which they are going to processed.
    The bids are then allocated, but unfortunately there are only 3 spaces in plot 15 that can be allocated. As a result, we use the priority listing to determine which bidder gets what.
     (booking table)
    At this stage, I can say that I am stuck, there are two things that I want to do, both of which involve reusing the results of the query at step 2.
     (bid table)
    The bidders that have their job allocated should see: their bid.status updated
    from Queued to Allocated,
    the bid.position should
    be set to 0,
    and their job_id should
    be set to the booking they have been allocated (i.e. booking.id).
    The bidders that have not had their jobs allocated should see: their bid.status remain
    as Queued, and their bid.position should
    be set to 0 in
    preparation for the method to run again
    The difficulty I am having is in stage 3, how do I determine which jobs have been allocated and which ones have not, and then run the necessary SQL queries in order to make the updates?
    My code so far is as follows:
    // STEP 1a - SELECT BIDS
    string query =
    "SELECT t1.operator_id, t1.datetime, t1.plot_id, t1.position, t2.market_access FROM bid t1 " +
    "JOIN operator t2 ON t1.operator_id = t2.id WHERE t1.status='Queued' AND t1.postcode=@postcode " +
    "ORDER BY t2.market_access ASC, t1.datetime ASC";
    var bidList = new List<BidList>();
    var cmd = new MySqlCommand(query, _connection);
    cmd.Parameters.AddWithValue(("@postcode"), _plot);
    MySqlDataReader dataReader = cmd.ExecuteReader();
    while (dataReader.Read())
    var item = new BidList
    OperatorId = dataReader["operator_id"] + "",
    PlotId = dataReader["plot_id"] + "",
    Position = dataReader["position"] + "",
    Datetime = dataReader["datetime"] + "",
    MarketAccess = dataReader["market_access"] + "",
    bidList.Add(item);
    dataReader.Close();
    // STEP 1b - SET PRIORITIES
    for (var i = 0; i < bidList.Count; i++)
    var position = i + 1;
    bidList[i].Position = position.ToString();
    query = "UPDATE bid SET position=@position WHERE status='Queued' AND postcode=@postcode AND operator_id=@operator_id;";
    cmd = new MySqlCommand(query, _connection);
    cmd.Parameters.AddWithValue(("@position"), position);
    cmd.Parameters.AddWithValue(("@postcode"), _plot);
    cmd.Parameters.AddWithValue(("@operator_id"), bidList[i].OperatorId);
    cmd.ExecuteNonQuery();
    dataReader.Close();
    // STEP 2 - ALLOCATE JOBS ACCORDING TO PRIORITY
    foreach (var t in bidList)
    query = "SELECT operator_id, plot_id, status FROM booking " +
    "WHERE status='open' AND postcode=@postcode AND operator_id='0'" +
    "ORDER BY datetime ASC;" +
    "UPDATE booking SET operator_id=@operator_id, status='Allocated' " +
    "WHERE (plot_id=@plot_id AND operator_id='0' AND status='Open') LIMIT 1;";
    cmd = new MySqlCommand(query, _connection);
    cmd.Parameters.AddWithValue(("@operator_id"), t.OperatorId);
    cmd.Parameters.AddWithValue(("@postcode"), _plot);
    cmd.Parameters.AddWithValue(("@plot_id"), t.PlotId);
    cmd.ExecuteNonQuery();
    dataReader.Close();
    // STEP 3
    CloseConnection();

    I can't tell.  When modifying row(s) you have to be able to uniquely be able to identify the row(s) in the database you want to modify.  That is why I recommended the other day to use DataAdapter instead of the DataReader.  You can with the
    reader, but you need to unique identify the rows.
    I can't tell from the limited amount of data you posted if in table 2 that there is only one row with the same operator id and plot id.  It looks like in table 2 the 'id' number is unique.  When working with a database with multiple tables you
    need to be able to link tables together with primary keys (columns wit unique values).  If the database isn't designed properly then it is impossible to do some operations.  So you always have to make sure you design a database properly.
    jdweng
    When you say table 2 are you referring to the bid or booking table?
    Here is the table structure for the bid table
    Here is the table structure for the booking table
    Hope it helps makes things clearer!

  • How to use the result of a sql query for a max () function

    Hi
    I wrote a query on which i wrote
    "select max(id) from users "
    how can i use the returned value.
    if i made the var name ="userid"
    can it be userid.rows[0] or what.
    thnx for any help

    Hi!
    The result of this query will be the max ID of users' IDs.
    Let say we have:
    String sql="select max(users.id) from users";
    Statement st = ctx.conn.createStatement();
    ResultSet rs = st.executeQuery(sql);
    rs.next();     
    So you can get the max Id in the following way:     
    int maxId=rs.getInt("id");
    Regards,
    Rossi

  • Edit the  results list in  sql developer 1.5

    Hi
    is there someone that know if it is possible to make a querry in sql developer and then edit in the results list?
    I have tryed but can not se how.
    In my company we are using both toad 9.7 and sql developer and the users would like to update the data in the results list .It is possible in toad and can be done with less risk.
    thank you
    steen ostersen

    No, but you can vote on http://htmldb.oracle.com/pls/otn/f?p=42626:39:2887745563411926::NO::P39_ID:4902 to add weight for implementing sooner...
    Have fun,
    K.

  • How to send two seperate queries from OBI and combine the results

    Hello all,
    I am trying to understand how to combine results of two queries in OBI. Here is the scenario.
    There are three tables, User, Security Roles joined though a Bridge Table Role_User
    Each user has multiple roles, The roles to which a user has access is identified by a flag column with value T or else it will have value F.
    I am trying to create an analysis as below
    User Id
    Roles with Access
    Roles without Access
    So column 2 will show all the roles with flag T for particular user and column 2 will show all the roles with flag F for same user.
    I tried creating two Fact tables and using Filter condition on the flag value, but in analysis I could only use one at a time. When I add both the columns , I get error as None of the fact table are compatible with the query request. I do have hierarchies created for the dimensions and assigned them in the content level for all dims and facts.
    Any hint will be highly appreciated.
    Thanks  

    Got the solution. I am posting it here in case anyone face similar issue.
    I added this SQL code in the advanced tab:
    Select A.saw_0 saw_0, A.saw_1 saw_1, B.saw_1 saw_2
    FROM( Select Col1 saw_0,Col2 saw_1 FROM Table1) A LEFT OUTER JOIN
    (Select Col1 saw_0,Col2 saw_1 FROM Table2) B
    on A.saw_0=B.saw_0
    I created to Logical Facts using same source with two different filter conditions and used them with sub-query as above
    Ref: OBIEE Interviews: Reports

  • How to view the result of any SQL script

    Hi
    I am working on Oracle 10 g Express Edition.I have an explicit cursor code ,a very basic one.I want to know how can i view result of the script.When i Save and run the script i get nothign on the window.
    I am pasting the script for the Reference.
    Code
    Declare
    CURSOR c_p IS
    select p_id from PRODUCTS;
    v_pid PRODUCTS.p_id%type;
    Begin
    OPEN c_p;
    Loop
    FETCH c_p into v_pid;
    Exit when c_p%NOTFOUND;
    Dbms_output.put_line(v_pid);
    End loop;
    CLOSE c_p;
    End;
    Prod_id Prod_category Prod_name Prod_price
    123456 Games Sony PS3 599.99
    234567 Games Sony PSP 249.99
    345678 Games Nintendo Wii 249.99
    456789 Games Microsoft Xbox 360 349.99
    567890 Computer Microsoft Vista 349.99

    Hi,
    Try like this:
    SQL> set serveroutput on
    SQL> DECLARE
      2  CURSOR c_p IS
      3  select first_name from EMP;
      4  v_name EMP.first_name%type;
      5  Begin
      6  OPEN c_p;
      7  Loop
      8  FETCH c_p into v_name;
      9  Exit when c_p%NOTFOUND;
    10  Dbms_output.put_line(v_name);
    11  End loop;
    12  CLOSE c_p;
    13  End;
    14
    15
    16  /
    Steven
    Neena
    Lex
    Alexander
    Bruce
    David
    Valli
    Diana
    Nancy
    Daniel
    John
    Ismael
    Jose Manuel
    Luis
    Den
    Alexander
    Shelli
    Sigal
    Guy
    Karen
    Matthew
    Adam
    Payam
    Shanta
    Kevin
    Julia
    Irene
    James
    Steven
    Laura
    Mozhe
    James
    TJ
    Jason
    Michael
    Ki
    Hazel
    Renske
    Stephen
    John
    Joshua
    Trenna
    Curtis
    Randall
    Peter
    John
    Karen
    Alberto
    Gerald
    Eleni
    Peter
    David
    Peter
    Christopher
    Nanette
    Oliver
    Janette
    Patrick
    Allan
    Lindsey
    Louise
    Sarath
    Clara
    Danielle
    Mattea
    David
    Sundar
    Amit
    Lisa
    Harrison
    Tayler
    William
    Elizabeth
    Sundita
    Ellen
    Alyssa
    Jonathon
    Jack
    Kimberely
    Charles
    Winston
    Jean
    Martha
    Girard
    Nandita
    Alexis
    Julia
    Anthony
    Kelly
    Jennifer
    Timothy
    Randall
    Sarah
    Britney
    Samuel
    Vance
    Alana
    Kevin
    Donald
    Douglas
    Jennifer
    Michael
    Pat
    Susan
    Hermann
    Shelley
    William
    PL/SQL procedure successfully completed.
    SQL>Cheers,

  • Making Buttons appear depending on the results of a SQL Query

    I need some help here I am still working on a time clock program
    I need help with the clock in and out buttons i need to know how to make
    the clock in button appear only if they are not clocked in. But I can not seem
    to make the sql statement or maybe my code is wrong, it needs to just get a
    count to see if they have any entries that have 0 in the hoursworked column
    and if so then it needs to just display the clock out if not then just the clockin button needs to be displayed this was my orignal code that was not working
    <%   
        String statement = "select count(*) as cnt from TimeSheet Where idnum = " + session.getAttribute("IDNUM");
        stmt.execute(statement);
        rs = stmt.getResultSet();
        rs.next();
        int num = rs.getInt("cnt");
        if (num == 0 || num == null)
        {%>
            <tr>
                <td><input type="submit" value="Clock In" name="button"></td>
            </tr>
        <%}
        else
        {%>
            <tr>
                <td><input type="submit" value="Clock Out" name="button"></td>
            </tr>
         <% } %>but it did not work it would only display the clock out button so i need to figure this out so that the user can not clock into the program twice to get double hours and so forth.

    Does it even compile ?Yes, it wouldnt, not even in 1.5
    it needs to just get a
    count to see if they have any entries that have 0 in the hoursworked column
    and if so then it needs to just display the clock out if not then just the clockin button needs to be displayed in which case,
    1. your sql is not correct.
    2. session.getAttribute("attrName") returns an Object - is the IDNUM column of type number
    (going by the fact that you have not enclosed the value in single quotes '')
    Assuming that you have a column called 'hoursworked' in table 'timesheet' and
    IDNUM is of type NUMBER
    <%
         Integer idNum = (Integer)session.getAttribute("IDNUM");
         //from the OP ::  get a count to see if they have any entries that have 0 in the hoursworked column
         String statement = "select count(*) as CNT from TIMESHEET where IDNUM = " + idNum + " and HOURSWORKED = 0 ";
         //remaining stuff :: Look out for the error pointed out by Pgeuens
         cheers,
    ram.

  • Derived Table How can I give the results of this SQL Line an Explicit Name.

    I am trying to create a derived table and I get the error
    "each calculated column must have an explicit name"
    I added the as shiptype to the end of the line and that did not work. Any thoughts?
    shiptype = case when araddr.invno is not null then 'ADDR' else (case when arcadr.custno is not null then 'CADR' else 'CUST' end) end as shiptype,
    Thanks
    Jeff

    Sure,
    Here is the complete query.
    This query works fine is sql query analyzer but when I put it in the designer I get the error.
    SELECT      'C' as tableId,
    '' as StartMast,
    armast.invno as invno,
    armast.invdte as invdte,
    armast.ponum as ponum,
    armast.ordate as ordate,
    armast.shipvia as shipvia,
    armast.fob as fob,
    armast.ornum as ornum,
    armast.disc as Idisc,
    armast.taxrate as Itaxrate,
    armast.tax as tax,
    armast.invamt as invamt,
    armast.disamt as disamt,
    armast.paidamt as paidamt,
    armast.balance as balance,
    armast.dtepaid as dtepaid,
    armast.pterms as pterms,
    armast.arstat as arstat,
    armast.artype as artype,
    armast.notes as notes,
    armast.salesmn as salesmn ,
    '' as StartBill,
    arcust.custno,
    arcust.company as billComp,
    arcust.contact as billaddr1,
    arcust.address1 as billaddr2,
    arcust.address2 as billaddr3,
    arcust.city as billcity,
    arcust.addrstate as billstate,
    arcust.zip as billzip,
    arcust.country as billcountry,
    arcust.phone as billphone,
    arcust.faxno as billfaxno,
    rtrim(cast(arcust.email as varchar(2000))) as billemail,
    '' as StartShip,
    armast.tosw,
    armast.cshipno,
    shiptype = case when araddr.invno is not null then 'ADDR' else (case when arcadr.custno is not null then 'CADR' else 'CUST' end) end,
    shipcomp = left(case when araddr.invno is not null then araddr.company else (case when arcadr.custno is not null then arcadr.company else arcust.company end) end + space(35),35),
    shipaddr1 = left(case when araddr.invno is not null then araddr.address1 else (case when arcadr.custno is not null then arcadr.contact else arcust.contact end) end + space(30),30),
    shipaddr2 = left(case when araddr.invno is not null then araddr.address2 else (case when arcadr.custno is not null then arcadr.address1 else arcust.address1 end) end + space(30),30),
    shipaddr3 = left(case when araddr.invno is not null then araddr.address3 else (case when arcadr.custno is not null then arcadr.address2 else arcust.address2 end) end + space(30),30),
    shipcity = left(case when araddr.invno is not null then araddr.city else (case when arcadr.custno is not null then arcadr.city else arcust.city end) end + space(20),20),
    shipstate = left(case when araddr.invno is not null then araddr.addrstate else (case when arcadr.custno is not null then arcadr.addrstate else arcust.addrstate end) end + space(10),10),
    shipzip = left(case when araddr.invno is not null then araddr.zip else (case when arcadr.custno is not null then arcadr.zip else arcust.zip end) end + space(10),10),
    shipcntry = left(case when araddr.invno is not null then araddr.country else (case when arcadr.custno is not null then arcadr.country else arcust.country end) end + space(15),15),
    '' as StartCmnt,
    armast.commid as commid,
    arcomm.comment as CommCmnt,
    arscom.comment as ScomCmnt,
    invCmnt = isnull(
                case
                      when armast.commid = 'MISC' then arcomm.comment
                      when len(rtrim(armast.commid)) > 0 then arscom.comment
                      else ''
                end
    '' as StartTran,
    artran.tranlineno,
    artran.item,
    artran.loctid,
    artran.Descrip,
    artran.intmemo,
    artran.custmemo,
    artran.qtyord,
    artran.qtyshp,
    artran.price,
    artran.disc as ldisc,
    artran.taxrate as ltaxrate,
    artran.extprice,
    artran.taxable,
    artran.arstat as linestat,
    artran.artype as linetype
    FROM armast
    LEFT JOIN artran ON artran.invno = armast.invno
    Left JOIN arcust ON arcust.custno = armast.custno
    Left JOIN arcomm ON arcomm.invno = armast.invno
    Left JOIN arscom ON arscom.commid = armast.commid
    LEFT JOIN araddr ON araddr.invno = armast.invno
    LEFT JOIN arcadr ON arcadr.custno = armast.custno AND arcadr.cshipno = armast.cshipno
    WHERE (armast.invdte >= getdate() - 180 OR len(rtrim(armast.arstat)) = 0)
          AND armast.invno <> '_RECEIPT'
          AND len(rtrim(armast.currhist)) = 0
          AND armast.custno = 'TJS-01'
    Union All
    SELECT      'H' as tableId,
    '' as StartMast,
    arymst.invno as invno,
    arymst.invdte as invdte,
    arymst.ponum as ponum,
    arymst.ordate as ordate,
    arymst.shipvia as shipvia,
    arymst.fob as fob,
    arymst.ornum as ornum,
    arymst.disc as Idisc,
    arymst.taxrate as Itaxrate,
    arymst.tax as tax,
    arymst.invamt as invamt,
    arymst.disamt as disamt,
    arymst.paidamt as paidamt,
    arymst.balance as balance,
    arymst.dtepaid as dtepaid,
    arymst.pterms as pterms,
    arymst.arstat as arstat,
    arymst.artype as artype,
    arymst.notes as notes,
    arymst.salesmn as salesmn ,
    '' as StartBill,
    arcust.custno,
    arcust.company as billComp,
    arcust.contact as billaddr1,
    arcust.address1 as billaddr2,
    arcust.address2 as billaddr3,
    arcust.city as billcity,
    arcust.addrstate as billstate,
    arcust.zip as billzip,
    arcust.country as billcountry,
    arcust.phone as billphone,
    arcust.faxno as billfaxno,
    rtrim(cast(arcust.email as varchar(2000))) as billemail,
    '' as StartShip,
    arymst.tosw,
    arymst.cshipno,
    shiptype = case when aryadr.invno is not null then 'YADR' else (case when arcadr.custno is not null then 'CADR' else 'CUST' end) end,
    shipcomp = left(case when aryadr.invno is not null then aryadr.company else (case when arcadr.custno is not null then arcadr.company else arcust.company end) end + space(35),35),
    shipaddr1 = left(case when aryadr.invno is not null then aryadr.address1 else (case when arcadr.custno is not null then arcadr.contact else arcust.contact end) end + space(30),30),
    shipaddr2 = left(case when aryadr.invno is not null then aryadr.address2 else (case when arcadr.custno is not null then arcadr.address1 else arcust.address1 end) end + space(30),30),
    shipaddr3 = left(case when aryadr.invno is not null then aryadr.address3 else (case when arcadr.custno is not null then arcadr.address2 else arcust.address2 end) end + space(30),30),
    shipcity = left(case when aryadr.invno is not null then aryadr.city else (case when arcadr.custno is not null then arcadr.city else arcust.city end) end + space(20),20),
    shipstate = left(case when aryadr.invno is not null then aryadr.addrstate else (case when arcadr.custno is not null then arcadr.addrstate else arcust.addrstate end) end + space(10),10),
    shipzip = left(case when aryadr.invno is not null then aryadr.zip else (case when arcadr.custno is not null then arcadr.zip else arcust.zip end) end + space(10),10),
    shipcntry = left(case when aryadr.invno is not null then aryadr.country else (case when arcadr.custno is not null then arcadr.country else arcust.country end) end + space(15),15),
    '' as StartCmnt,
    arymst.commid as commid,
    arcomm.comment as CommCmnt,
    arscom.comment as ScomCmnt,
    invCmnt = isnull(
                case
                      when arymst.commid = 'MISC' then arcomm.comment
                      when len(rtrim(arymst.commid)) > 0 then arscom.comment
                      else ''
                end
    '' as StartTran,
    arytrn.tranlineno,
    arytrn.item,
    arytrn.loctid,
    arytrn.Descrip,
    arytrn.intmemo,
    arytrn.custmemo,
    arytrn.qtyord,
    arytrn.qtyshp,
    arytrn.price,
    arytrn.disc as ldisc,
    arytrn.taxrate as ltaxrate,
    arytrn.extprice,
    arytrn.taxable,
    arytrn.arstat as linestat,
    arytrn.artype as linetype
    FROM arymst
    LEFT JOIN arytrn ON arytrn.invno = arymst.invno
    Left JOIN arcust ON arcust.custno = arymst.custno
    Left JOIN arcomm ON arcomm.invno = arymst.invno
    Left JOIN arscom ON arscom.commid = arymst.commid
    LEFT JOIN aryadr ON aryadr.invno = arymst.invno
    LEFT JOIN arcadr ON arcadr.custno = arymst.custno AND arcadr.cshipno = arymst.cshipno
    WHERE (arymst.invdte >= getdate() - 180 OR (len(rtrim(arymst.arstat)) = 0 AND arymst.invno in (select invno FROM armast where len(rtrim(arstat)) = 0)))
          AND arymst.invno <> '_RECEIPT'
          AND arymst.custno = 'TJS-01'

  • Get data from PL/SQL block and generate the data file in UNIX

    Hi All
    i was executing the following code block from Unix Shell Script. The following code was generating the file count_curdate.txt with all require infomrations. The query gives number of records , group by partition_dt
    ABC=`sqlplus -s <<EOF > count_curdate.txt
    uname/paswd@connectstring
    SET HEADING OFF;
    SELECT COUNT(*)||','||partition_dt from XYZ group by partition_dt;
    exit;
    END`
    But now i need to change the above code to use dbms_application_info.set_module in it. Could someone let me know how to generate the file using PL/SQL block in Shell Script. I tried writing following code, but it generate count_curdate.txt file with 0 bytes.
    ABC=`sqlplus -s <<EOF > count_curdate.txt
    uname/paswd@connectstring
    set serveroutput on;
    SET HEADING OFF;
    set feedback off;
    BEGIN
         dbms_application_info.set_module ('shm.ksh','get count by day');
         FOR reccur IN (SELECT COUNT(*)||','||partition_dt as "dcount" from XYZ group by partition_dt);
         LOOP
              DBMS_OUTPUT.PUT_LINE(reccur.dcount);
         END LOOP;
    end;     
    exit;
    END`

    OK, try this:
    ABC=`sqlplus -s <<EOF > count_curdate.txt
    uname/paswd@connectstring
    set serveroutput on;
    SET HEADING OFF;
    set feedback off;
    BEGIN
    dbms_application_info.set_module ('shm.ksh','get count by day');
    FOR reccur IN (SELECT COUNT(*)||','||partition_dt dcount from XYZ group by partition_dt);
    LOOP
    DBMS_OUTPUT.PUT_LINE(reccur.dcount);
    END LOOP;
    dbms_application_info.set_module (NULL,NULL);
    end;
    exit;
    EOF`Or this:
    ABC=`sqlplus -s <<EOF > count_curdate.txt
    uname/paswd@connectstring
    set serveroutput on;
    SET HEADING OFF;
    set feedback off;
    BEGIN
    dbms_application_info.set_module ('shm.ksh','get count by day');
    END;
    SELECT COUNT(*)||','||partition_dt dcount from XYZ group by partition_dt;
    BEGIN
    dbms_application_info.set_module (NULL,NULL);
    END;
    exit;
    EOF`Edited by: SeánMacGC on May 11, 2009 6:13 AM

  • Where the PL/SQL blocks is stored

    Hello,
    Is there any table like where the last
    complied PL/SQL block is stored in a database.
    Thanks and regards
    shawlin

    I'm not sure exactly what you are asking. If you are looking for the source code (USER_SOURCE, ALL_SOURCE, DBA_SOURCE). If you are looking for the last compile date/time (USER_OBJECTS, ALL_OBJECTS, DBA_OBJECTS).

  • Error in PL/SQL Block of Trigger

    Hi all,
    I have written a trigger whose PL/SQL block contains a simple select statment among many other statements.
    Now I find that, if the select statement returns no rows the trigger does not continue its operation further and aborts there itself. And if the select statement returns some rows, then it works fine.
    I tried to execute a simplified PL/SQL block of the trigger in SQL*Plus and following were the results:
    declare
    tempdate date;
    begin
    select trdt into tempdate from inv_trans;
    if sql%notfound then
    null;
    end if;
    end;
    When no data is present in inv_trans table, the result was:
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at line 4
    And when the table inv_trans had data, the result was:
    PL/SQL procedure successfully completed.
    Why is the piece of code flashing an error when I have already given a treatment if no data is found.
    Why is it taking "No Data in table" as an abnormal condition and not normal?
    THanks in advance
    Warm Regards
    Manu

    In your case you have to use a cursor:
    declare
      cursor c_cur is
        select trdt from inv_trans;
      r_cur   c_cur%rowtype;
    begin
      open c_cur;
      fetch c_cur into r_cur;
      if c_cur%notfound then
    [pre]                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for