Unions in stored procedures

We've been still using 8i but just had an instance of 9i put up in our development region. We're trying to take a dynamic sql statement with many unions and create a stored procedure. I understand this was a problem in 8i. We're still getting ambiguous error messages when trying to compile in 9i. Should the sql be in the construct of a cursor? Any suggestions would be appreciated.
Thanks,
Roger

Odd that they didn't install 10g, if the aim is to try out new features.
I have never come across any problems with set operators in dynamic SQL. Do you have any more details?
btw the minimum changes to the earlier example to get it to work would result in something like:
CREATE OR REPLACE PROCEDURE showemployee
     ( where_in IN VARCHAR2 := NULL )
IS
     TYPE emp_rectype IS RECORD
     ( empno emp.empno%TYPE
     , ename emp.ename%TYPE );
     TYPE SYS_REFCURSOR IS REF CURSOR;  -- Can be removed in 9i
     c_emp SYS_REFCURSOR;
     curs_rec EMP_RECTYPE;
BEGIN
     OPEN c_emp FOR
     'SELECT EMPNO, ENAME FROM EMP WHERE '|| NVL(where_in, '1=1');
     LOOP
          FETCH c_emp INTO curs_rec;
          EXIT WHEN c_emp%NOTFOUND;
          DBMS_OUTPUT.PUT_LINE(curs_rec.ename ||' '||curs_rec.empno);
     END LOOP;
     CLOSE c_emp;
END;
/

Similar Messages

  • How to Store the result sets of a stored procedure that is returning more that one result set in two different table ?

    Hi Experts,
       I have on stored procedure which returns mote than one resultset i want that to store in two different temp table how can achieve this in SQL server.
     following is the stored procedure and table that i need to create.
    create procedure GetData as begin select * from Empselect * from Deptend 
    create table #tmp1 (Ddeptid int, deptname varchar(500),Location varchar(100))
    Insert into #tmp1 (Ddeptid , deptname ,Location )
    exec GetData
    create table #tmp (empid int , ename varchar(500),DeptId int , salary int)
    Insert into #tmp (empId,ename,deptId,salary)
    exec GetData
    Niraj Sevalkar

    You cant get two resultsets out of SP like this. The workaround is to merge and bring the resultsets.
    For this number of columns as well as corresponding datatypes have to be compatible. Also you will need one additional column which indicates resultset value. Then use this as filter to get your desired resultset out
    create procedure GetData as
    begin
    select 'resultset1' as Cat,*,.. N columns from Emp
    union all
    select 'resultset2' as Cat,*,.. N columns from Dept
    end
    create table #tmp1 (Ddeptid int, deptname varchar(500),Location varchar(100))
    Insert into #tmp1 (Ddeptid , deptname ,Location )
    Select column1,column2,column3
    from OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
    Integrated Security=SSPI','Execute yourdb..GetData')
    WHERE Cat = 'resultset1'
    create table #tmp (empid int , ename varchar(500),DeptId int , salary int)
    Insert into #tmp (empId,ename,deptId,salary)
    Select column1,column2,column3, column4
    from OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
    Integrated Security=SSPI','Execute yourdb..GetData')
    WHERE Cat = 'resultset2'
    also see
    http://sqlblogcasts.com/blogs/madhivanan/archive/2007/11/26/select-columns-from-exec-procedure-name-is-this-possible.aspx
    Another method is to populate table with relevant resultset within procedure itself and then select from the table directly outside.
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • How do I insert multiple values into different fields in a stored procedure

    I am writing a Stored Procedure where I select data from various queries, insert the results into a variable and then I insert the variables into final target table. This works fine when the queries return only one row. However I have some queries that return multiple rows and I am trying to insert them into different fields in the target table. My query is like
    SELECT DESCRIPTION, SUM(AMOUNT)
    INTO v_description, v_amount
    FROM SOURCE_TABLE
    GROUP BY DESCRIPTION;
    This returns values like
    Value A , 100
    Value B, 200
    Value C, 300
    The Target Table has fields for each of the above types e.g.
    VALUE_A, VALUE_B, VALUE_C
    I am inserting the data from a query like
    INSERT INTO TARGET_TABLE (VALUE_A, VALUE_B, VALUE_C)
    VALUES (...)
    How do I split out the values returned by the first query to insert into the Insert Statement? Or do I need to split the data in the statement that inserts into the variables?
    Thanks
    GB

    "Some of the amounts returned are negative so the MAX in the select statement returns 0 instead of the negative value. If I use MIN instead of MAX it returns the correct negative value. However I might not know when the amount is going to be positive or negative. Do you have any suggestions on how I can resolve this?"
    Perhaps something like this could be done in combination with the pivot queries above, although it seems cumbersome.
    SQL> with data as (
      2        select  0 a, 0 b,  0 c from dual   -- So column a has values {0, 1, 4},
      3  union select  1 a, 2 b, -3 c from dual   --    column b has values {0, 2, 5},
      4  union select  4 a, 5 b, -6 c from dual ) --    column c has values {0, -3, -6}.
      5  --
      6  select  ( case when max.a > 0 then max.a else min.a end) abs_max_a
      7  ,       ( case when max.b > 0 then max.b else min.b end) abs_max_b
      8  ,       ( case when max.c > 0 then max.c else min.c end) abs_max_c
      9  from    ( select  ( select max(a) from data ) a
    10            ,       ( select max(b) from data ) b
    11            ,       ( select max(c) from data ) c
    12            from      dual ) max
    13  ,       ( select  ( select min(a) from data ) a
    14            ,       ( select min(b) from data ) b
    15            ,       ( select min(c) from data ) c
    16            from      dual ) min
    17  /
    ABS_MAX_A  ABS_MAX_B  ABS_MAX_C
             4          5         -6
    SQL>

  • How to retrieve the outer parameter of a stored procedure in XSQL page

    I have to call a stored procedure in the xsql page that returns a resultset (ie. oracle table/record type) through an outer paramter. Is there any built-in xsql action tag available to get the parameter and present
    it in xml on the page? please help, thanks.

    You cant get two resultsets out of SP like this. The workaround is to merge and bring the resultsets.
    For this number of columns as well as corresponding datatypes have to be compatible. Also you will need one additional column which indicates resultset value. Then use this as filter to get your desired resultset out
    create procedure GetData as
    begin
    select 'resultset1' as Cat,*,.. N columns from Emp
    union all
    select 'resultset2' as Cat,*,.. N columns from Dept
    end
    create table #tmp1 (Ddeptid int, deptname varchar(500),Location varchar(100))
    Insert into #tmp1 (Ddeptid , deptname ,Location )
    Select column1,column2,column3
    from OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
    Integrated Security=SSPI','Execute yourdb..GetData')
    WHERE Cat = 'resultset1'
    create table #tmp (empid int , ename varchar(500),DeptId int , salary int)
    Insert into #tmp (empId,ename,deptId,salary)
    Select column1,column2,column3, column4
    from OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
    Integrated Security=SSPI','Execute yourdb..GetData')
    WHERE Cat = 'resultset2'
    also see
    http://sqlblogcasts.com/blogs/madhivanan/archive/2007/11/26/select-columns-from-exec-procedure-name-is-this-possible.aspx
    Another method is to populate table with relevant resultset within procedure itself and then select from the table directly outside.
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • WITH clause in a stored procedure

    Hi, i have the following code for a stored procedure:
    create or replace
    PROCEDURE DISP_ORDER
    ( param1 IN VARCHAR2
    , param2 OUT Types.cursor_type
    ) AS
    BEGIN
    WITH itemall as (select * from rep_order)
    open param2 for select * from itemall;
    END DISP_ORDER;
    this produce an error
    PL/SQL:SQL statement ignored
    Question: Is the WITH clause not allowed in stored procedure?
    Thanks
    PS: cursor_type is defined, the code is only a example!

    WITH comes after the OPEN
    SQL> var c refcursor
    SQL> begin
      2      open :c for
      3          with test_data as
      4              (
      5              select 1 n from dual union all
      6              select 2 n from dual union all
      7              select 3 n from dual
      8              )
      9          select * from test_data;
    10  end;
    11  /
    PL/SQL procedure successfully completed.
    SQL> print c
             N
             1
             2
             3
    SQL>

  • With clause in a stored procedure with update

    create table TEMP_STAGE as
    (select '111111' student_id, 'N' TMP_TEST FROM DUAL
    UNION
    select '111111' student_id, 'N' TMP_TEST FROM DUAL
    UNION
    select '222222' student_id, 'N' TMP_TEST FROM DUAL
    CREATE OR REPLACE PROCEDURE TEMP_SEC_TEST
    AS
    BEGIN
    UPDATE TEMP_STAGE S
    SET S.TMP_TEST = 'Y'
    WHERE STUDENT_ID IN
    WITH MARK AS
    SELECT '111111' STUDENT_ID FROM DUAL
    select STUDENT_ID from MARK
    END;
    I have a huge sql statement with several 'with' tables in the statement...It works if I execute it as a script but it does not work when I put it in a stored procedure.
    When I execute the above it gives me an error...
    Error Syntax Check (8:9)
    Found 'MARK' expecting .....
    It gives me an error at the wth Mark as line....
    I have to do it in the stored procedure as the statement is very complicated...
    Please help.

    What tool are you using to create the procedure? Error Syntax Check (8:9) is not an Oracle error, nor as far as I know from any Oracle product.
    It works just fine in sqlplus.
    SQL> CREATE procedure my_p AS
      2  BEGIN
      3     UPDATE t
      4     SET descr = 'Un'
      5     WHERE id IN (WITH tmp AS (
      6                     SELECT 1 x FROM dual)
      7                  SELECT x FROM tmp);
      8  END;
      9  /
    Procedure created.
    SQL> SELECT * FROM t;
            ID DESCR
             1 One
    SQL> exec my_p;
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM t;
            ID DESCR
             1 UnJohn

  • SSIS 2012 ETL is failing only at one server (No BIDS) but running successfully from BIDS on different sever . In this ETL, I have used Stored Procedure in OLEDB Source.

    Hi Guys,
    SSIS 2012 ETL is failing only at one server (No BIDS) but running successfully from BIDS on different sever . In this ETL, I have used Stored Procedure in OLEDB Source.
    Note: I have couple of ETLs developed in 2005 using same logic and upgraded to 2012, working perfectly.
    I am getting Error Message:
    SSIS
    Error Code
    DTS_E_OLEDBERROR. 
    An OLE DB
    error has occurred.
    Error code: 0x80004005.
    An
    OLE DB
    record is available. 
    Source: "Microsoft OLE DB Provider for SQL Server" 
    Hresult: 0x80004005 
    Description: "Error converting data type varchar to datetime.".
    Unable
    to retrieve
    column information
    from the data
    source. Make
    sure your target
    table in
    the database is
    available.
    "OLE DB Source"
    failed validation
    and returned
    validation status
    "VS_ISBROKEN".
    I tried below word around and found It is working perfectly.
    I loaded data into a table (dbo.TEMP) using Stored procedure and then I used this dbo.TEMP table in OLEDB source and then found no issue.
    MY SP Details: (This SP I am calling in OLEDB source of ETL) and when I run it from one server IT is working fine and when I run from ETL dedicated Server getting error:   Guys Help me out.
    USE
    [TEST_DB]
    GO
    SET
    ANSI_NULLS ON
    GO
    SET
    QUOTED_IDENTIFIER ON
    GO
    ALTER
    PROCEDURE  [DBO].[SP_TEST]
    --EXEC [DBO].[SP_TEST] '2014-09-30','2014-10-01'
    @FROMDATETIME
    DATETIME,
    @TODATETIME
    DATETIME
    AS
    SET
    NOCOUNT ON
    BEGIN
    DECLARE
    @FROMDATEKEY INT,
    @TODATEKEY INT,
    SET
    @FROMDATEKEY=
    CONVERT(VARCHAR(10),@FROMDATETIME,112)
    SET
    @TODATEKEY=
    CONVERT(VARCHAR(10),@TODATETIME,112)
    IF 1 = 1
    BEGIN
    SELECT
    CAST(NULL
    AS DATETIME) 
    AS TXN_DATE
    , CAST(NULL
    AS DATETIME
    ) AS PROCESS_DATE     
    , CAST(NULL
    AS money)
    AS  S1_AMT
    , CAST(NULL
    AS money)
    AS  S2_AMOUNT
    , CAST(NULL
    AS money)
    AS  S2_INVALID_AMOUNT
    , CAST(NULL
    AS money)
    AS  INVALID_MOVED_IN_VALID_S2_AMOUNT
    , CAST(NULL
    AS VARCHAR(20))
    AS SYSTEM_ID
    , CAST(NULL
    AS money)
    AS  S3_AMT
    END
    SELECT
    TXN_DATE
    ,PROCESS_DATE
    ,S1_AMT
    ,S2_AMOUNT
    ,S2_INVALID_AMOUNT
    ,INVALID_MOVED_IN_VALID_S2_AMOUNT
    ,SYSTEM_ID
    S3_AMT
    FROM
    DBO.TABLE_1
    WHERE TNX_DATE_KEY
    BETWEEN @FROMDATEKEY
    and @TODATEKEY
    UNION
    ALL
    SELECT
    TXN_DATE
    ,PROCESS_DATE
    ,S1_AMT
    ,S2_AMOUNT
    ,S2_INVALID_AMOUNT
    ,INVALID_MOVED_IN_VALID_S2_AMOUNT
    ,SYSTEM_ID
    S3_AMT
    FROM
    DBO.TABLE_2
    WHERE TNX_DATE_KEY
    BETWEEN @FROMDATEKEY
    and @TODATEKEY
    UNION
    ALL
    SELECT
    TXN_DATE
    ,PROCESS_DATE
    ,S1_AMT
    ,S2_AMOUNT
    ,S2_INVALID_AMOUNT
    ,INVALID_MOVED_IN_VALID_S2_AMOUNT
    ,SYSTEM_ID
    S3_AMT
    FROM
    DBO.TABLE_3
    WHERE TNX_DATE_KEY
    BETWEEN @FROMDATEKEY
    and @TODATEKEY
    END
    Data Source Mode: SQL Command for Variable
    "EXEC [DBO].[SP_TEST]  '"+ (DT_WSTR, 24) @[User::V_EXTRACT_FROM_DT]  +"','"+ (DT_WSTR, 24) @[User::V_EXTRACT_TO_DT]  +"'"
    Where variable @[User::V_EXTRACT_FROM_DT] and @[User::V_EXTRACT_TO_DT] is defined as DATETIME 
    Thanks Shiven:) If Answer is Helpful, Please Vote

    Hi,
    Yes you are right. At one sever where I was getting error, DateTime was in USA format and Where It was running successfully was in AUS format.
    I changed from USA to AUS and I did another changes:
    Data Source Mode: SQL
    Command
    EXEC  [DBO].[SP_TEST] 
    @FROMDATETIME = ?,
    @TODATETIME = ?
    and It is working fine.
    Thanks Shiven:) If Answer is Helpful, Please Vote

  • Wrapped in a function and/or stored procedure, recursive CTE stops working

    This query builds an hierarchical tree from a single table with the typical 
    value/reports_to_value columns. 
    When running in SQL manager returns like 7 records (note i'm avoiding infinite 
    loop by blocking top level value)
    WITH c 
    AS
        SELECT deptid, reports_to_dept
        FROM glo_tree
        WHERE deptid = '18538'
        UNION ALL
        SELECT t.deptid, t.reports_to_dept
        FROM glo_tree T  
        INNER JOIN c 
    ON t.deptid = c.reports_to_dept
        where t.deptid <> '00001'
    SELECT deptid  
    FROM c 
    However, the exact same query, if wrapped in a function and/or stored procedure, 
    returns 0 records (no error message whatsoever)
    CREATE FUNCTION [dbo].[checkDept] (@deptid varchar(16))
    RETURNS TABLE
    AS
    RETURN
        WITH c 
        AS
            SELECT  deptid, reports_to_dept
            FROM    glo_tree
            WHERE   deptid = @deptid
        UNION ALL
        SELECT  t.deptid, t.reports_to_dept
        FROM    glo_tree T  
        INNER JOIN c 
        ON      t.deptid = c.reports_to_dept
    SELECT deptid  
    FROM c 
    GO
    CREATE PROCEDURE [dbo].[getDept] (@deptid varchar(16))
    AS
        SELECT deptid
        FROM dbo.checkDept(@deptid)
    Then call them like:
    select * FROM checkDept('18538')exec getDept @deptid='18538'
    Both return nothing

    Thanks Patrick, i don't think it can do that, i call it like:
    select * FROM checkDept('18538')exec getDept @deptid='18538'Just to make sure, i've changed the function like:WHERE ltrim(rtrim(deptid)) = @deptidStill the same thing

  • Getting error when calling stored procedure

    I have created 2 stored procedures as follows
    set ANSI_NULLS ON
    set QUOTED_IDENTIFIER ON
    go
    ALTER PROCEDURE [dbo].[REAL_PUSH_UPDATE_REPORTS] AS
    BEGIN TRANSACTION
         DECLARE @cursor_contact_id bigint;
         DECLARE cursorContactId Cursor FOR SELECT distinct(contact_id) FROM [dbo].credit_reports WHERE loan_id IS NULL;
         OPEN cursorContactId;
         Fetch NEXT FROM cursorContactId INTO @cursor_contact_id;
    IF(@@FETCH_STATUS <> 0)
    PRINT 'There are no LOAN contacts are there with loan ID null, May be you have already executed this procedure'
         WHILE(@@FETCH_STATUS =0)
         BEGIN
    PRINT @cursor_contact_id;
              EXECUTE REAL_UPDATE_REPORTS @cursor_contact_id;
              Fetch NEXT FROM cursorContactId INTO @cursor_contact_id
         END
         CLOSE cursorContactId;
         DEALLOCATE cursorContactId;
         IF (@@Error = 0)
              BEGIN
                   COMMIT TRANSACTION;
              END
         ELSE
              BEGIN
                   ROLLBACK TRANSACTION;
              END
    set ANSI_NULLS ON
    set QUOTED_IDENTIFIER ON
    go
    ALTER PROCEDURE [dbo].[REAL_UPDATE_REPORTS] @initial_contact_id bigint AS
    BEGIN TRANSACTION
         DECLARE @loan_count bigint;
         DECLARE cursorLoanID Cursor FOR (SELECT l.loan_id loanIDList FROM (([dbo].loans l LEFT OUTER JOIN [dbo].loan_requests lr
    ON lr.loan_id=l.loan_id
    AND lr.contact_id = l.primary_borrower_id)
    LEFT OUTER JOIN [dbo].loan_codes lc
    ON l.loan_code_id = lc.loan_code_id) 
    WHERE (l.primary_borrower_id=@initial_contact_id)
    AND l.active=1  UNION  SELECT l.loan_id 
    FROM   [dbo].loans l LEFT OUTER JOIN [dbo].loan_requests lr
    ON lr.loan_id=l.loan_id LEFT OUTER JOIN [dbo].contacts c
    ON c.contact_id =l.primary_borrower_id
    WHERE (l.loan_id IN
    (SELECT cb.loan_id FROM coborrowers cb where contact_id =@initial_contact_id and active = 1))
    UNION
    SELECT l.loan_id 
    FROM   [dbo].loans l LEFT OUTER JOIN [dbo].loan_requests lr
    ON lr.loan_id=l.loan_id LEFT OUTER JOIN [dbo].contacts c
    ON c.contact_id =l.primary_borrower_id
    WHERE (l.loan_id IN (SELECT cs.loan_id
    FROM cosigners   cs where contact_id =@initial_contact_id and active = 1)) UNION
    SELECT g.loan_id  FROM   [dbo].groups g, [dbo].group_members gm,
    [dbo].loan_requests lr WHERE gm.group_id = g.group_id
    AND lr.loan_id = g.loan_id
    AND lr.contact_id = gm.secondary_borrower_id
    AND gm.secondary_borrower_id=@initial_contact_id and gm.active = 1) 
    ORDER BY loanIDList DESC;
         OPEN cursorLoanID;
         SET @loan_count = @@CURSOR_ROWS;
    PRINT @loan_count;
         IF(@loan_count > 0)     BEGIN
              DECLARE @loans_loan_id bigint;
              Fetch NEXT FROM cursorLoanID INTO @loans_loan_id;
              DECLARE @my_count bigint;
              SET @my_count=1;
              WHILE(@@FETCH_STATUS =0)
              BEGIN
                   DECLARE @temp_contact_id bigint;
                   DECLARE @temp_loan_id bigint;
                   SET @temp_contact_id = @initial_contact_id;
                   SET @temp_loan_id = @loans_loan_id;
                   IF(@my_count=@loan_count)
                        BEGIN
                             UPDATE [dbo].credit_reports SET loan_id = @temp_loan_id WHERE
    loan_id IS NULL AND contact_id = @initial_contact_id 
    AND NOT EXISTS (SELECT * FROM  [dbo].credit_reports
    WHERE contact_id = @initial_contact_id  AND
    loan_id=@temp_loan_id);
                        END
                   ELSE
                        BEGIN
                             INSERT INTO [dbo].credit_reports(contact_id,credit_bureau_id, credit_score, thirty_days_late,
    sixty_days_late, ninety_days_late, currently_negative, amount_past_due,
    inquiries_six_mos, public_records, collections, total_accounts_balance,
    total_mthly_pymts, report_file, report_gu_id, data_entry_by, data_entry_date,
    loan_id)  SELECT contact_id,credit_bureau_id, credit_score, thirty_days_late,
    sixty_days_late, ninety_days_late, currently_negative, amount_past_due,
    inquiries_six_mos, public_records, collections, total_accounts_balance,
    total_mthly_pymts, report_file, report_gu_id, data_entry_by,
    data_entry_date,@temp_loan_id   FROM [dbo].credit_reports WHERE contact_id
    = @initial_contact_id AND loan_id IS NULL
    AND NOT EXISTS (SELECT * FROM
    [dbo].credit_reports WHERE contact_id=@initial_contact_id AND
    loan_id=@temp_loan_id);
    END
    Fetch NEXT FROM cursorLoanID INTO @loans_loan_id;               
    SET @my_count = @my_count + 1;
              END
    close cursorLoanID
    deallocate cursorLoanID
              IF (@@Error = 0)
                   BEGIN
                        COMMIT TRANSACTION;
                        PRINT 'Success for contactID :'+CONVERT(varchar(50),@initial_contact_id);
                   END
              ELSE
                   BEGIN
                        ROLLBACK TRANSACTION;
                        PRINT 'Failed for contactID :'+CONVERT(varchar(50),@initial_contact_id);
                   END
         END
         ELSE
         BEGIN
              ROLLBACK;
              PRINT 'NO Loans For the contactID :'+CONVERT(varchar(50),@initial_contact_id);
         ENDnow the problem is
    i have executed 2 procedures saperately thn its ok while im calling im getting
    Msg 16915, Level 16, State 1, Procedure REAL_UPDATE_REPORTS, Line 5
    A cursor with the name 'cursorLoanID' already exists.
    Msg 16905, Level 16, State 1, Procedure REAL_UPDATE_REPORTS, Line 6
    The cursor is already open.Please let me know the reason...
    Thank you.
    Message was edited by:
    User71408

    What the heck, that's fun..
    I for one, have never seen T-sql or whatever it's called.
    Looking at it, it seems that a
    close cursorLoanID
    deallocate cursorLoanID
    is missing from the ELSE section doing the rollback.
    But, only guessing
    Fun, fun, fun

  • Stored procedure, returning array output

    i am new to oracle and stored procedure and i have tried to do this but, still no luck, can anyone help me out?
    my stored procedure & package is as follows;
    create or replace package prebooking
    is
        type tr_contract_data
        is
            record (
                    custcode  customer_all.custcode%TYPE        ,
                    des       rateplan.des%TYPE                 ,
                    dn_num    directory_number.dn_num%TYPE      ,
                    cd_sm_num contr_devices.cd_sm_num%TYPE
        type tt_contract_data
        is
            table of tr_contract_data
            index by binary_integer;
        procedure customer_data (
                                    pc_custcode             in  customer_all.custcode%TYPE,
                                    pc_customer_name        out varchar2                  ,
                                    pc_customer_address_1   out varchar2                  ,
                                    pc_customer_address_2   out varchar2                  ,
                                    pc_user_lastmod         out varchar2
        procedure contract_data (
                                    pc_custcode             in  customer_all.custcode%TYPE,
                                    pt_contract_data        out tt_contract_data
    end prebooking;
    drop public synonym prebooking;
    create public synonym prebooking for prebooking;
    grant execute on prebooking to wpa;
    -- EOF: PREBOOKING.plh
    create or replace package body prebooking
    is
        procedure customer_data (
                                    pc_custcode             in  customer_all.custcode%TYPE,
                                    pc_customer_name        out varchar2                  ,
                                    pc_customer_address_1   out varchar2                  ,
                                    pc_customer_address_2   out varchar2                  ,
                                    pc_user_lastmod         out varchar2
        is
            cursor c_customer_data ( pc_custcode customer_all.custcode%TYPE )
            is
                select ccline1  || ' ' || ccfname || ' ' || cclname         customer_name,
                       ccstreet || ' ' || ccaddr2 || ' '     || ccaddr3 ||
                                   ' ' || cccity  || ' zip ' || cczip   ||
                                   ' ' || ccline4                           customer_address_1,
                       ccstate  || ' ' || ccline6                           customer_address_2,
                       b.user_lastmod                                       user_lastmod
                from ccontact_all a,
                     customer_all b
                where b.customer_id = a.customer_id
                  and a.ccbill = 'X'
                  and b.custcode = pc_custcode;
        begin
            open c_customer_data ( pc_custcode );
            fetch c_customer_data into pc_customer_name     ,
                                       pc_customer_address_1,
                                       pc_customer_address_2,
                                       pc_user_lastmod      ;
            close c_customer_data;
        end customer_data;
        procedure contract_data (
                                    pc_custcode             in  customer_all.custcode%TYPE,
                                    pt_contract_data        out tt_contract_data
        is
            cursor c_contract_date ( pc_custcode customer_all.custcode%TYPE )
            is
                select h.custcode,
                       g.des,
                       e.dn_num,
                       d.cd_sm_num
                from curr_co_status      a,
                     contract_all        b,
                     contr_services_cap  c,
                     contr_devices       d,
                     directory_number    e,
                     rateplan            g,
                     customer_all        h
                where h.customer_id = b.customer_id
                  and b.co_id = a.co_id
                  and b.co_id = c.co_id
                  and b.co_id = d.co_id
                  and c.dn_id = e.dn_id
                  and b.tmcode = g.tmcode
                  and c.cs_deactiv_date is null
                  and h.custcode = pc_custcode;
        begin
            for c in c_contract_date ( pc_custcode )
            loop
                pt_contract_data (nvl (pt_contract_data.last, -1) + 1).custcode  := c.custcode ;
                pt_contract_data (     pt_contract_data.last         ).des       := c.des      ;
                pt_contract_data (     pt_contract_data.last         ).dn_num    := c.dn_num   ;
                pt_contract_data (     pt_contract_data.last         ).cd_sm_num := c.cd_sm_num;
            end loop;
        end contract_data;
    end prebooking;
    -- EOF: PREBOOKING.plhand i am using the following php code to do this
    <?php
      $conn=OCILogon("USER", "USER", "DB");
      if ( ! $conn ) {
         echo "Unable to connect: " . var_dump( OCIError() );
         die();
      $collection_name = 1.1;     
      $stmt = OCIParse($conn,"begin PREBOOKING.CONTRACT_DATA(:INN, :OUTT); end;");
      OCIBindByName($stmt, ":INN", $collection_name, 200);
      //OCIBindByName($stmt, ":", $collection_desc, 100);
      $blobdesc = OCINewDescriptor($conn, OCI_D_LOB);
      OCIBindByName($stmt, ":OUTT", $blobdesc, -1, OCI_B_BLOB);
      $blobdesc->WriteTemporary($binary_junk, OCI_B_BLOB);
      OCIExecute($stmt);
      OCILogoff($conn);
    ?>the error i get when i run this code is;
    Warning: OCI-Lob::writetemporary() [function.writetemporary]: Cannot save a lob that is less than 1 byte in C:\apachefriends\xampp\htdocs\POSP\oci53.php on line 18
    Fatal error: Call to undefined function OCIDefineArrayOfStruct() in C:\apachefriends\xampp\htdocs\POSP\oci53.php on line 19

    Hi Varun,
    To combine the first xml-formatted column to one XML, If you want to do that in SQL server, you can reference the below sample.
    CREATE PROC proc1 -- the procedure returning the resultset with 3 columns
    AS
    DECLARE @XML1 VARCHAR(MAX),
    @XML2 VARCHAR(MAX),
    @XML3 VARCHAR(MAX);
    SET @XML1='<person><name>Eric</name></person>'
    SET @XML2='<book><name>war and peace</name></book>'
    SET @XML3='<product><name>product1</name></product>'
    SELECT @XML1 AS col1,1 AS col2,2 AS col3
    UNION ALL
    SELECT @XML2,2,3
    UNION ALL
    SELECT @XML3,2,3
    GO
    CREATE PROC proc2
    AS
    DECLARE @TbL TABLE(id INT IDENTITY, col1 VARCHAR(MAX),col2 INT,col3 INT)
    INSERT INTO @TbL EXEC proc1
    SELECT id as '@row' ,cast(col1 as xml) FROM @TbL FOR XML PATH('XML'),TYPE
    GO
    EXEC proc2
    DROP PROC proc1,proc2
    /*output
    <XML row="1">
    <person>
    <name>Eric</name>
    </person>
    </XML>
    <XML row="2">
    <book>
    <name>war and peace</name>
    </book>
    </XML>
    <XML row="3">
    <product>
    <name>product1</name>
    </product>
    </XML>
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • MaxDB 7.6 carshes on calling stored procedure with driver 7.6

    Hi All,
    Recently I upgraded MaxDB from v7.5 to v7.6 after several hiccups I am almost done but one strange problem remains. I have a stored procedure which is used for generating Bill Of Material (recursive cursor). The said stored procedure uses some views (if that matters at all). If I call that stored procedure using JDBC driver v7.5 then all works well and if JDBC driver v7.6 is used to call the stored procedure it simply crashes the database. Does not it sound strange
    Does anyone have any clues?
    Thanks,
    Vinod

    Hi Marco,
    Here is the stored procedure, which causes database crash-
    START -
    [code]CREATE DBPROC shortlist_all_month (IN schedule VARCHAR(14)) RETURNS CURSOR AS
        $CURSOR = 'bom';
        BEGIN
        CREATE TABLE temp.bom_view
          (bom_version, main_item_code, sub_item_code, sub_item_qty, bom_item_remarks) AS
          SELECT bom_version, main_item_code, sub_item_code, sub_item_qty, bom_item_remarks
          FROM suman.mfg_bom_m
          WHERE bom_version = (SELECT MAX(bom_version) FROM suman.mfg_bom_m M
                        WHERE M.main_item_code = mfg_bom_m.main_item_code);
        DECLARE :$CURSOR CURSOR FOR
        WITH RECURSIVE PX (main, sub, qty, super_main) AS
           (SELECT main_item_code, sub_item_code, sub_item_qty, main_item_code
             FROM temp.bom_view WHERE main_item_code IN (
                SELECT schedule_plan_item FROM suman.ppc_schedule_m WHERE schedule_code = :schedule)
            UNION ALL
            SELECT main_item_code, sub_item_code, sub_item_qty, super_main
             FROM temp.bom_view B, suman.PX
             WHERE sub = B.main_item_code)
        SELECT sub AS sub_item_code, item_item_desc, item_mfg_flag, stock_item_qty,
         SUM(qty * schedule_plan_qty) AS req_qty, (stock_item_qty - SUM(qty * schedule_plan_qty)) AS short_qty
         FROM suman.PX B, suman.ppc_schedule_m S, suman.mfg_item_p I, suman.mfg_item_stock V
         WHERE B.super_main = S.schedule_plan_item
         AND schedule_code = :schedule
         AND B.sub = I.item_item_code
         AND B.sub = V.stock_item_code
         AND V.stock_dept_code = 'DP0008'
         GROUP BY sub, item_item_desc, item_mfg_flag, stock_item_qty
         HAVING SUM(qty * schedule_plan_qty) > 0 ORDER BY 3, 1;
        DROP TABLE TEMP.BOM_VIEW;
    END;[/code]----
    END -
    This used to work fine for last >4 years. See if you can find something fishy. I will try to give a runnable test case to reproduce the crash.
    Thanks,
    Vinod

  • What happens to the report if the underlying stored procedure to execute the report take atleast 3 hrs to run

    Hi,
    I have a report which is calling a stored procedure..
    Stored procedure exceutes 4-5 stored procedure and then returns the count each procedure it ran using union all statement... The stored procedure takes around 3-4 hrs to run because it is looking at quarterly data and YTD data.
    So once the report is kicked off and the procedure behind it runs and runs how will communicate to the report to show the final data... the final data will just be 5 rows with counts.
    I think we are running into a issue where the stored procedure runs and runs and then the report goes into la la land and has no clue what to do...
    Can you please shed some light on this..
    Thanks
    Karen

    Hi Karen,
    When we render a report, the report would process the following procedures:
    Open connections to data source and reading data rows from data extensions for all datasets, means retrieve data. Then process the engine requests, including the tablix, grouping, sorting, filtering, aggregations and subreport processing, means process report.
    Finally, render the report, including the pagination modules and on-demand expression evaluations.
    So the report rending has to wait until the stored procedure is executed. To improve the performance, we can consider the three aspects:
    Improve the performance of the stored procedures. Such as index and join. For better support, I suggest you can post a new thread about this issue in Transact-SQL forum at:
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/home?forum=transactsql. It is appropriate and more experts will assist you.
    Simplify the report. For example, avoid including a reference to [&TotalPages] or any complex expressions in the page header and page footer. For more details, please see the following document:
    http://technet.microsoft.com/en-us/library/bb522806(v=sql.105).aspx
    Using cashing if you have a long-running query that cannot be tuned further. For more details, please refer to the following article:
    http://msdn.microsoft.com/en-us/library/ms159241(v=sql.110).aspx
    Hope this helps.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Tsql stored procedure - passing multiple variables

    Hi,
    I have a dropdown field on a form that allows for multiple
    selects. When I process the form, I currently use CF to dynamically
    generate the sql WHERE clause creating as many AND statements as
    needed.
    I'm migrating to MS SQL 2005 and Stored Procedures on the db.
    I'm trying to create a stored procedure that effectively uses tsql
    to do what CF was doing previously (creating the WHERE clause).
    In the code below, I am passing a char(22) variable called
    Channel. The code below was my initial attempt at trying to create
    the WHERE clause. Most of the code is focused on extracting out the
    individual "Channel" entities. Any thoughts on how to pull this
    together would be GREATLY appreciated!
    I'm need help on the SELECT side, ultimately I'm selecting
    "regions", from "Syndicated", the WHERE is based on the "Channels"
    passed.
    Thanks,
    cfwild

    Hi,
    This was quite the adventure trying to figure this out. I
    learned quite a bit about tsql. Here is the final procedure:
    CREATE PROCEDURE dbo.uspSelectSyndicatedRegion
    @TablePrefix char(7),
    @Category varchar(100),
    @Channel varchar(2000)
    AS
    BEGIN
    SELECT DISTINCT S.Region
    FROM Syndicated S
    JOIN iter_charlist_to_tbl(@Channel, DEFAULT) M
    ON S.Channel = M.str
    UNION
    SELECT ''
    ORDER BY S.Region
    END

  • Display select in a stored procedure

    Hello,
    I have a select statement that I wanna print in a stored procedure. The only way is to create a cursor in the SP, which holds the result of the select, and then iterate through the lines and print each line using dbms_output.put_line?
    Thanks.

    You can pass a ref cursor as an output parameter and print that.
    SQL> create or replace procedure p (p_c out sys_refcursor) as
      2  begin
      3    open p_c for
      4      with test_data as
      5      (
      6      select 1 n, 'a' s from dual union all
      7      select 2 n, 'b' s from dual union all
      8      select 5 n, 'x' s from dual
      9      )
    10      select n, s from test_data;
    11  end;
    12  /
    Procedure created.
    SQL> var c refcursor
    SQL> exec p(:c)
    PL/SQL procedure successfully completed.
    SQL> print c
             N S
             1 a
             2 b
             5 x

  • EXIT or RETURN in Stored Procedures

    Anyone,
    Should I use EXIT/RETURN/GOTO when in a stored procedure and I am trying to deal with EXCEPTION handling but need to exit out of stored proc handing back a value in an OUT variable to the calling procedure?
    I have been working with all three and I still seem to have a memory leak that causes a
    "ORA-03113: end-of-file on communication channel"
    Error after running the same procedures several times. I think this is related to the way I am exiting the procedure and the fact that I am in nested CURSORS.
    Any help would be greatly appreciated.
    Thanks,
    Miller

    The following example should help.
    SQL> VARIABLE MYVAR VARCHAR2
    SQL> DECLARE
      2  PROCEDURE TEST(p1_out OUT VARCHAR2) AS
      3  BEGIN
      4  SELECT 'X' INTO p1_out FROM
      5  DUAL
      6  UNION
      7  SELECT 'X' FROM DUAL;
      8  EXCEPTION
      9  WHEN TOO_MANY_ROWS THEN
    10   p1_out := 'Y';
    11  END;
    12  BEGIN
    13  TEST(:myvar);
    14  END;
    15  /
    PL/SQL procedure successfully completed.
    SQL> PRINT MYVAR
    MYVAR
    X
    SQL> ED
    Wrote file afiedt.buf
      1  DECLARE
      2  PROCEDURE TEST(p1_out OUT VARCHAR2) AS
      3  BEGIN
      4  SELECT 'X' INTO p1_out
      5  FROM  DUAL
      6  UNION ALL
      7  SELECT 'X' FROM DUAL;
      8  EXCEPTION
      9  WHEN TOO_MANY_ROWS THEN
    10   p1_out := 'Y';
    11  END;
    12  BEGIN
    13  TEST(:myvar);
    14* END;
    SQL> /
    PL/SQL procedure successfully completed.
    SQL> PRINT MYVAR
    MYVAR
    Y

Maybe you are looking for