Utl_file - exception handling when inserted in bulk.

Hi,
I am using Oracle 10gR2. I wanted to write data to a file. Due to huge number of records, I am collecting them into a collection, traversing e collection, appending the values in collection to a varchar variable with new line in a loop.If the array size is say 50, I will have 50 values in the Vatchar variable separated by CHR(10). and I will insert the variable using UTL_FILE.PUT so that 50 lines will be inserted with values into the file.
Now my query is if any one among those 50 values gives an exception, I feel all the 50 values can't be loaded. Please suggest exception handling in this case.
Regards,
Naveen Kumar.C.
Edited by: Naveen Kumar C on Sep 17, 2009 5:23 PM

You could use a CLOB in conjunction with UTL_FILE to write it out 32K at a time...
SQL> ed
Wrote file afiedt.buf
  1  DECLARE
  2    l_file    UTL_FILE.FILE_TYPE;
  3    l_clob    CLOB;
  4    l_buffer  VARCHAR2(32767);
  5    l_amount  BINARY_INTEGER := 32767;
  6    l_pos     INTEGER := 1;
  7  BEGIN
  8    BEGIN
  9      SELECT dbms_xmlgen.getxmltype('select * from emp natural join dept').getclobval()
10      INTO   l_clob
11      FROM   dual;
12    EXCEPTION
13      WHEN NO_DATA_FOUND THEN
14        RETURN;
15    END;
16    l_file := UTL_FILE.fopen('TEST_DIR', 'Sample2.txt', 'w', 32767);
17    LOOP
18      DBMS_LOB.read (l_clob, l_amount, l_pos, l_buffer);
19      UTL_FILE.put(l_file, l_buffer);
20      l_pos := l_pos + l_amount;
21    END LOOP;
22  EXCEPTION
23    WHEN NO_DATA_FOUND THEN -- occurs when end of CLOB reached
24      UTL_FILE.fclose(l_file);
25    WHEN OTHERS THEN
26      DBMS_OUTPUT.put_line(SQLERRM);
27      UTL_FILE.fclose(l_file);
28* END;
SQL> /
PL/SQL procedure successfully completed.
SQL>

Similar Messages

  • Exception Handling for inserts

    Hi,
    My requirement is to populate a table with values got by selecting columns from various table on join conditions. It works fine if all the rows inserted are unique. However if the row to be inserted is duplicate, it violates the uniqueness constraint.
    I want an exception wherein if select query returns 100 rows, of which 80 are already there in the table to be populated, it should just insert the 20 records.
    Below is the SP i wrote for the same. However, as soon as it meets exception condition, it just prints the condition and exits, without processing the rest of the records. Please look at the SP below and suggest a solution.
    create or replace
    PROCEDURE PP_CMC_TEST AS
    cursor c1 is
    (select cdu.subscription_id,max(cdu.account_id),max(s.subscription_versn_start_date),
    max(s.service_plan_id),max(sbp.billing_period_id),sysdate-1
    ,cdu.device_name, cdu.resource_id,sum(cdu.usage),max(cdu.unit_of_measurement)
    from
    subscriptions s, subscription_billing_period sbp, consolidated_daily_usage cdu
    where s.version_end_date is null and
    sysdate-1 between sbp.start_date and sbp.end_date and
    cdu.usage_date between sbp.start_date and sbp.end_date
    and s.subscription_id = cdu.subscription_id
    and sbp.subscription_id = cdu.subscription_id
    and sbp.subscription_id = s.subscription_id
    and s.subscription_versn_start_date=sbp.subscription_versn_start_date
    group by cdu.subscription_id,cdu.device_name, cdu.resource_id);
    a number;
    b number;
    c date;
    d number;
    e number;
    f date;
    g varchar2 (255);
    h number;
    i number;
    j varchar2(60);
    BEGIN
      OPEN c1;
        LOOP
            FETCH c1 INTO a,b,c,d,e,f,g,h,i,j;
             EXIT WHEN c1%NOTFOUND;
    insert into cmc_test
    (subscription_id,account_id,subscription_versn_start_date,service_plan_id,billing_period_id,curr_date,
    device_name,resource_id,usage,unit_of_measurement) values
    (a,b,c,d,e,f,g,h,i,j);
        END LOOP; 
                                 EXCEPTION
        WHEN DUP_VAL_ON_INDEX
          THEN
          DBMS_OUTPUT.PUT_LINE('DUPLICATE RECORD FOUND');
          commit;
        CLOSE c1; 
    END PP_CMC_TEST;Edited by: BluShadow on 07-Feb-2012 09:03
    added {noformat}{noformat} tags (for what it was worth).  Please read {message:id=9360002} and learn to do this yourself in future.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Using SQL you would create an error table and modify the INSERT to log the errors. See the 'Inserting Into a Table with Error Logging' section of http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_9014.htm. Note this approach will not work if you are using direct path loads since the log table won't be used.
    If you are going to use PL/SQL for this then what you want is to use BULK COLLECT and then a FORALL with a SAVE EXCEPTIONS clause.
    >
    A. BULK COLLECT INTO plsqlTable LIMIT 5000 - These are your new records you want to INSERT
    B. FORALL ... SAVE EXCEPTIONS - This is the INSERT query to insert the new records
    C. Use a bulk exception handler. Any record in the FORALL that causes an exception will have it's index put into the bulk exception array. In the bulk exception handler you can loop through the array and access the records that caused the error using the index into the plsqlTable and do any error logging you need to do.
    >
    The bulk exception array will have the plsql table index of the row that caused the error. You can index into the plsql table (see Step A above) to access the record and then log it, INSERT it into a duplicates table or whatever you want.
    The important thing is that the records that do not have errors will still get processed. Similar result to what will happen if you use SQL and an error table.

  • Exception Handling - WHEN OTHERS

    Good Day to All,
    When i am running a procedure in TOAD-Expert... it says below message.
    *'Avoid using a WHEN OTHERS clause in an exception section without any other specific handlers.'*
    PROCEDURE...
    IS
    BEGIN
    EXCEPTION
    WHEN OTHERS THEN
    ROLLBACK;
    -- Checking whether cursor is open
       IF cur%ISOPEN THEN
        CLOSE cur;
       END IF;
      UPDATE TABLE
      SET COL..
      WHERE ...
       COMMIT;
       RAISE;
    END procedure;

    The manner in which you are dealing with the exception is not wrong. Your handler does a couple of things:
    - rollbacks the existing transaction as failed
    - attempts resource protection (guard against resource leakage)
    - logs the error
    - re-raises the exception
    None of these are invalid actions when dealing with an exception.
    A suggestion though - move the UPDATE out of the exception and create a procedure that performs the logging for you (as an autonomous transaction). This way you have a reusable logging code unit that can be called from anywhere in your code.
    Resource protection for explicit cursors are also not that critical in PL/SQL - as cursor handles that go out of scope are automatically released. The exception being a ref cursor handle. Of course, you need to resource protect other handles (like socket and file handles). And seeing that PL/SQL does not offer resource protection blocks, the only alternative is to use the "+when OTHERS+" exception handler for that.

  • Exception handling when no execuble bindings available in PageDefinition?

    Currently I'm showcasing a simple authentication example to one of our clients. The example consists of the following :
    * a simple AuthenticationFilter setup in my web.xml
    * a simple (V1 ... not V2) DataAction with a modelReference property pointing to the correct pageModel.
    The pageModel looks like this :
    <?xml version="1.0" encoding="UTF-8" ?>
    <pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel"
    version="10.1.3.36.73" id="indexPageDef"
    Package="my.demo.package.pageDefs">
    </pageDefinition>
    As you can see ... it does not contain any executable bindings.
    The DataAction has a "onLogon(DataActionContext ctx)" method which calls out to a method on my ApplicationModule (pretty similar to the Jheadstart authentication example). The method gets actually called and it performs the authentication perfectly. BUT .. when (for example) the username is not correct, it will throw a JboException.
    When I try to login again (this time with the correct credentials) and no (new) exceptions are thrown, the old exception is still on the stack ! !
    I tried forcing a bindingContainer.resetInputState() but that didn't help. After a period of digging in the source code I found out the following :
    // oracle.adf.model.binding.DCBindingContainer
    public void resetInputState() {
    // other code
    if (mExecutables == null)
    return;
    // other code
    mExcs = null;
    Some extra info : mExcs points to an ArrayList which contains the exceptions in the bindingcontainer. mExecutables point to a HashMap which contains the executable bindings in the bindingcontainer (~PageDef).
    In other words : if the PageDef does not contain any executable bindings, the stack of exceptions is not reset. Which in my case is what's happening.
    If I change the code of de DCBindingContainer to the following :
    public void resetInputState() {
    // other code
    if (mExecutables == null)
    // could not be sooner, because it is used later on...
    mExcs = null;
    return;
    // other code
    mExcs = null;
    If I run my demo again I see that the stack of exceptions is actually cleared even though I do not have any executable bindings in my PageDef.
    So, my question is : is it correct behaviour that resetInputState() does not clear the exceptions if I have an empty PageDefinition ?

    ** bump **

  • Exception Handling when calling a PHP Webservice

    I followed a great tutorial on setting calling PHP services from ABAP ([Accessing arbitrary databases from within ABAP using a PHP data hub and web services|Accessing arbitrary databases from within ABAP using a PHP data hub and web services]).   Unfortunately I'm getting occassional CX_AI_SYSTEM_FAULT exceptions and I don't know how to handle them gracefully.
    I'm calling the web service ABAP code from an RFC function which for some reason doesn't allow TRY/CATCH statements (I get a message saying "During RFC/update, no exception classes can be used".) 
    I'd be happy enough just to ignore the error since it's currently dumping users out of order entry.
    To make matters more complicated, I can't TRY/CATCH my own RFC since I'm calling it from GuiXT
    I'd really appreciate help on this; I'm pretty stumped.
    Thanks,
    Lee

    Well, to answer my own question, I found an ugly workaround.
    Change attribute from "Remote-enabled" to "Normal Function", add the TRY/CATCH logic.  Then call this function from the "real" RFC.
    Off to program like it's 1979!
    Lee

  • Mediator exception handling when no data found in database

    hi Guys,
    I am using DB adapter in a composite and using a mediator to invoke them, however not getting how to send the response back,
    in case there is NO_DATA_FOUND error.
    waiting for response
    thanks
    Yatan

    Yatan
    As far as i know a DB adapter will not throw no_data_found exception if it is not able to get rows from database it will just initialize the output variable with null. But yes in case of call to procedure or function it may cause that you should handle then and there only.
    Let us know what exactly is the issue you are facing.
    Thanks
    AJ

  • Exception handling when invoke ejb

    Hi,
    I call ejb like this:
    try {
          MyBeanHome beanHome = .. //jndi lookup 
          MyBean bean = beanHome .create();
          HashMap h = bean.chargeFee(data);
          bean.remove();
    } catch (
    }there are a lot exceptions: NamingException, CreationException, RemoteException, RemoveException (I don't have application exception).
    I am thinking I catch the RemoveException first, since it happened after the chargeFee is called, and chargeFee is already been executed, so I deal it differently with the other Exceptions, since they heppend before or during the chargeFee executed, I treat it as not been executed.
    Is it the right way to handle the exceptions? Thanks

    It's difficult to answer you question because the intent is not known.
    I would suggest to write down all possible exceptions and the actions to be taken. Try to pass on as many exceptions as possible to the client. I know I might be getting a lot for flake for this statement but catching too many exception makes the code look complicated. If you don't know what to do with an exception then just don't catch it.
    If Pet Store example is complicated for you then try looking at Avitek Medical records example that comes bundled with BEA weblogic 8.1. You can install it for free and the example is just great.
    - Roger

  • Exception Handling In BPEL  By using Catch Blocks or Fault Policies Or Both

    I have a confusion regarding
    Exception handling :
    When Should i go for 1)Catch Block (Remote , or binding ) in bpel for exception handling .
    2)Fault Policy , Fault binding.xml
    Currently iam using catch blocks , but even fault policy is good , but can i use both...
    Currently in My bpel ,when any error occurs i have to send a error notification by Email .
    Currently i have exposed the email service which shuts emails and write a file with errored Message.
    Hence if any error i will catch i in a parent BPEL, i will just invoke the above email, service .
    So anybody can help me by giving the suggestion how to go for the best approach
    Edited by: anantwag on Mar 23, 2011 6:31 AM

    Currently in My bpel ,when any error occurs i have to send a error notification by Email .
    Currently i have exposed the email service which shuts emails and write a file with errored Message.Seeing your use case I will suggest you to use fault handling framework (fault policy). Fault handling framework should be used where you need generic error handling framework which handles all the faults occured in any composite component. Generally BPEL catch block should be used to propagate error info/fault back to the client/to fault handling framework or to consume an error
    Regards,
    Anuj

  • Exception handling in ODI - common exception handling framework

    Hi,
    I need to come up with a common exception handling framework in an environment where ESB and ODI are being used for interfacing and ELT operations. I am of the opinion that
    1. I am not able to find any documentation wrt exception handling when ODI is used? Can some one help me with some pointers?
    2, When I come up with a common exception handling framework using BPEL, will I be able to invoke the same from ODI.
    Thanks,
    Mahesh

    Thanks for the reply Allan. I haven't used BusinessWorks.
    I did go through this thread before and here's my understanding.
    1. ESB provides the ability of error handling (client management API) but not the exception handling i.e. I can't redirect the flow in case there is an exception in my primary flow. Am I right with my understanding?
    2. Error handling ability of ESB is limited to retryable exceptions viz-a-viz asynchrounous ESB processes (e.g. database listener not up) where in the process can be retried. Am I right here?
    Thanks,
    Mahesh

  • Exception handling with fault message type not working

    Hi,
    I have a sync proxy to proxy scenario and I have created a fault MT and specified in the outbound and Inbound service interface...
    *In Inbound proxy I have the following code--*......
    RAISE EXCEPTION TYPE z_cx_test_fault
    EXPORTING
    standard = l_standard_data.
    In the sender side abap code which calls the outbound proxy I have the follwing code -
    CATCH cx_ai_system_fault INTO lo_cx_ai_system_fault.
    txt = lo_cx_ai_system_fault->get_text( ).
    WRITE txt.
    CATCH z_cx_test_fault INTO lo_cx_test_fault.
    txt = lo_cx_standard_message_fault->get_text( ).
    WRITE txt.
    CATCH cx_ai_application_fault INTO lo_cx_ai_application_fault.
    txt = lo_cx_ai_application_fault->get_text( ).
    WRITE txt.
    when i test the inbound proxy separately I get the custom fault message properly...
    however when i run the proxy to proxy sync scenario and the custom exceptionz_cx_test_fault  is raised inside the receiver proxy .......control goes to CATCH cx_ai_application_fault    and not CATCH  z_cx_test_fault .
    I understand that cx_ai_application_fault is the super class of all the exception class but why does control go to its exception handling when a custom exception is raised...
    Edited by: hema T on Feb 26, 2012 1:16 PM
    Edited by: hema T on Feb 26, 2012 1:17 PM

    Hi
    I tried changing the sequence also but it did not work...
    I can see an appropriate response coming from the receiver in SXMB_MONI of PI...this response has the "fault response "
    "fault detail" data that I want.....however when the control goes to the sender why does it go to CATCH CX_AI_APPLICATION_FAULT and not not my CATCH z_cx_test_fault .
    My observation - If I change the scenario to SOAP to Proxy sync..then the sender SOAP client gets the appropriate custom fault message back.
    Edited by: hema T on Feb 27, 2012 1:17 PM
    Edited by: hema T on Feb 27, 2012 1:17 PM

  • Exception handling - Common exception handling framework

    Hi,
    I need to come up with a common exception handling framework in an environment where ESB and ODI are being used for interfacing and ELT operations. I am of the opinion that
    1. A generic exception handling framework can be built using BPEL and can be invoked from ESB. Is my understanding correct?
    2. Are there any ways that we can build this framework using ESB itself? I opinion that it's not possible as there is no concept of try-catch?
    3. I am not able to find any documentation wrt exception handling when ODI is used? Can some one help me with some pointers?
    4, When I come up with a common exception handling framework, will I be able to invoke the same from ODI.
    Thanks,
    Mahesh

    Thanks for the reply Allan. I haven't used BusinessWorks.
    I did go through this thread before and here's my understanding.
    1. ESB provides the ability of error handling (client management API) but not the exception handling i.e. I can't redirect the flow in case there is an exception in my primary flow. Am I right with my understanding?
    2. Error handling ability of ESB is limited to retryable exceptions viz-a-viz asynchrounous ESB processes (e.g. database listener not up) where in the process can be retried. Am I right here?
    Thanks,
    Mahesh

  • Exception handling in  in insert statemnt

    i am inserting values in to a table in a procedure.for insert statemnt what are the possible exceptions that may occur.
    how to handle exceptions for that insert statement(other than when others)

    user639995 wrote:
    is there any possiblity to use if sql%rowcount = 0 then
    RAISE e1;
    like thisNot for an insert statement, no.
    sql%rowcount returns the number of rows effected by a DML statement.
    For any of the statements you can only check sql%rowcount after the DML statement successfully executes, and it will only return a 0 if no rows were effected by that DML statement e.g. if an update effected no rows or an insert ... select ... actually inserted no rows etc.
    If an exception occurs during a DML statement then execution will pass directly to the exception handler so you won't have the opportunity to test for sql%rowcount after the statement.
    You should have an exception handler for expected exceptions.
    If an exception is not expected then you should let your code raise it up so it is seen and not handled.
    example of defining exceptions for non-named error numbers...
    SQL> create table x (x number);
    Table created.
    SQL> insert into x values ('x');
    insert into x values ('x')
    ERROR at line 1:
    ORA-01722: invalid number
    SQL> set serverout on
    SQL> declare
      2    ex_not_number exception;
      3    pragma exception_init(ex_not_number, -1722);
      4  begin
      5    insert into x values (1);
      6    commit;
      7    insert into x values ('A');
      8    commit;
      9  exception
    10    when ex_not_number then
    11      dbms_output.put_line('An attempt to insert a value that is not a number was made.');
    12  end;
    13  /
    An attempt to insert a value that is not a number was made.
    PL/SQL procedure successfully completed.
    SQL> select * from x;
             X
             1
    SQL>Further details on exception handling here:
    [PL/SQL 101 : Exception Handling|http://forums.oracle.com/forums/thread.jspa?threadID=697262&tstart=50]

  • EXCEPTION HANDLE IN BULK COLLECT

    HOW WILL I HANDLE EXCEPTION IN BULKCOLLECT
    SUPPOSE IF NO DATA IS FOUND I WANT TO SET A VARIABLE IS 0 THEN THERE AFTER OTHER STAEMENT ARE PROCESSED
    ELSE ALL STATEMENT ARE PROCESSED.

    when you use bulk collect with select into, it doesn't raise any exception when no data is found. you can simple COUNT the elements in your array structure (in which you have collected the data) to check whether any rows have been processed or not.
    like...
      1  DECLARE
      2    TYPE tt IS TABLE OF VARCHAR2(100) INDEX BY PLS_INTEGER;
      3    v_tt tt;
      4  BEGIN
      5    SELECT ename BULK COLLECT INTO v_tt FROM emp WHERE empno = 7899;
      6    DBMS_OUTPUT.PUT_LINE(v_tt.COUNT);
      7* END;
    11:43:37 SQL> /
    0
    PL/SQL procedure successfully completed.

  • Bulk Fetch Exception Handling

    How do you use exception in BULK FETCH?

    <How do you use exception in BULK FETCH?>
    I've never gotten an exception in a bulk fetch, aside from getting the error when the query select list does not match the variables its being selected into. I think that normal exception handling would apply.
    I'm assuming you mean BULK COLLECTS. Did you mean bulk binds, the FORALL statement?

  • Exception handling for all the insert statements in the proc

    CREATE PROCEDURE TEST (
    @IncrStartDate DATE
    ,@IncrEndDate DATE
    ,@SourceRowCount INT OUTPUT
    ,@TargetRowCount INT OUTPUT
    ,@ErrorNumber INT OUTPUT
    ,@ErrorMessage VARCHAR(4000) OUTPUT
    ,@InsertCase INT --INSERT CASE INPUT
    WITH
    EXEC AS CALLER AS
    BEGIN --Main Begin
    SET NOCOUNT ON
    BEGIN TRY
    DECLARE @SuccessNumber INT = 0
    ,@SuccessMessage VARCHAR(100) = 'SUCCESS'
    ,@BenchMarkLoadFlag CHAR(1)
    ,@BenchmarkFlow INT
    ,@MonthYearStart DATE
    ,@MonthYearEnd DATE
    ,@StartDate DATE
    ,@EndDate DATE
    /* Setting the default values of output parameters to 0.*/
    SET @SourceRowCount = 0
    SET @TargetRowCount = 0
    /*Setting the Start and end date for looping */
    SET @MonthYearStart = @IncrStartDate;
    SET @MonthYearEnd = @IncrEndDate;
    /* Setting the @InsertCase will ensure case wise insertion as this sp will load data in different tables
    @InsertCase =0 means data will be inserted in the target TAB1
    @InsertCase =1 means data will be inserted in the target TAB2
    @InsertCase =2 means data will be inserted in the target TAB3
    @InsertCase =3 means data will be inserted in the target TAB4
    @InsertCase =4 means data will be inserted in the target TAB5
    @InsertCase =5 means data will be inserted in the target TAB6
    if @InsertCase =0
    WHILE (@MonthYearStart <= @MonthYearEnd)
    BEGIN
    SET @StartDate = @MonthYearStart;
    SET @EndDate = @MonthYearEnd;
    /* Delete from target where date range given from input parameter*/
    DELETE FROM TAB1
    WHERE [MONTH] BETWEEN MONTH(@StartDate) AND MONTH(@EndDate)
    AND [YEAR] BETWEEN year(@StartDate) and year(@EndDate)
    /*Insert data in target-TAB1 */
    BEGIN TRANSACTION
    INSERT INTO TAB1
    A,B,C
    SELECT
    A,BC
    FROM XYZ
    COMMIT TRANSACTION
    SET @MonthYearStart = DATEADD(MONTH, 1, @MonthYearStart)
    SELECT @TargetRowCount = @TargetRowCount + @@ROWCOUNT;
    END -- End of whileloop
    END TRY
    BEGIN CATCH
    IF @@TRANCOUNT>0
    ROLLBACK TRANSACTION
    SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE();
    END CATCH
    END--End of Main Begin
    I have the above proc inserting data based on parameters  where in @InsertCase  is used for case wise execution.
     I have written the whole proc with exception handling using try catch block.
    I have just added one insert statement here for 1 case  now I need to add further insert  cases
    INSERT INTO TAB4
                    A,B,C
    SELECT
                                    A,BC
    FROM XYZ
    INSERT INTO TAB3
                    A,B,C
    SELECT
                                    A,BC
    FROM XYZ
    INSERT INTO TAB2
                    A,B,C
    SELECT
                                    A,BC
    FROM XYZ
    I will be using following to insert further insert statements 
    if @InsertCase =1 
    I just needed to know where will be my next insert statement should be fitting int his code so that i cover exception handling for all the code
    Mudassar

    Hi Erland & Mudassar, I have attempted to recreate Mudassar's original problem..here is my TABLE script;
    USE [MSDNTSQL]
    GO
    /****** Object: Table [dbo].[TAB1] Script Date: 2/5/2014 7:47:48 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[TAB1](
    [COL1] [nvarchar](1) NULL,
    [COL2] [nvarchar](1) NULL,
    [COL3] [nvarchar](1) NULL,
    [START_MONTH] [int] NULL,
    [END_MONTH] [int] NULL,
    [START_YEAR] [int] NULL,
    [END_YEAR] [int] NULL
    ) ON [PRIMARY]
    GO
    Then here is a CREATE script for the SPROC..;
    USE [MSDNTSQL]
    GO
    /****** Object: StoredProcedure [dbo].[TryCatchTransactions1] Script Date: 2/5/2014 7:51:33 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE PROCEDURE [dbo].[TryCatchTransactions1] (
    @IncrStartDate DATE
    ,@IncrEndDate DATE
    ,@SourceRowCount INT OUTPUT
    ,@TargetRowCount INT OUTPUT
    ,@ErrorNumber INT OUTPUT
    ,@ErrorMessage VARCHAR(4000) OUTPUT
    ,@InsertCase INT --INSERT CASE INPUT
    WITH
    EXEC AS CALLER AS
    BEGIN --Main Begin
    SET NOCOUNT ON
    BEGIN TRY
    DECLARE @SuccessNumber INT = 0
    ,@SuccessMessage VARCHAR(100) = 'SUCCESS'
    ,@BenchMarkLoadFlag CHAR(1)
    ,@BenchmarkFlow INT
    ,@MonthYearStart DATE
    ,@MonthYearEnd DATE
    ,@StartDate DATE
    ,@EndDate DATE
    /* Setting the default values of output parameters to 0.*/
    SET @SourceRowCount = 0
    SET @TargetRowCount = 0
    /*Setting the Start and end date for looping */
    SET @MonthYearStart = @IncrStartDate;
    SET @MonthYearEnd = @IncrEndDate;
    /* Setting the @InsertCase will ensure case wise insertion as this sp will load data in different tables
    @InsertCase =0 means data will be inserted in the target TAB1
    @InsertCase =1 means data will be inserted in the target TAB2
    @InsertCase =2 means data will be inserted in the target TAB3
    @InsertCase =3 means data will be inserted in the target TAB4
    @InsertCase =4 means data will be inserted in the target TAB5
    @InsertCase =5 means data will be inserted in the target TAB6
    IF @InsertCase =0
    WHILE (@MonthYearStart <= @MonthYearEnd)
    BEGIN
    SET @StartDate = @MonthYearStart;
    SET @EndDate = @MonthYearEnd;
    /* Delete from target where date range given from input parameter*/
    DELETE FROM TAB1
    WHERE START_MONTH BETWEEN MONTH(@StartDate) AND MONTH(@EndDate)
    AND START_YEAR BETWEEN year(@StartDate) and YEAR(@EndDate)
    /*Insert data in target-TAB1 */
    BEGIN TRANSACTION
    INSERT INTO TAB1 (COL1,COL2,COL3)
    VALUES ('Z','X','Y')
    SELECT COL1, COL2, COL3
    FROM TAB1
    COMMIT TRANSACTION
    SET @MonthYearStart = DATEADD(MONTH, 1, @MonthYearStart)
    SELECT @TargetRowCount = @TargetRowCount + @@ROWCOUNT;
    END -- End of whileloop
    END TRY
    BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
    SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE();
    END CATCH
    PRINT @SUCCESSMESSAGE
    END--End of Main Begin
    GO
    I am just trying to help --danny rosales
    UML, then code

Maybe you are looking for

  • I want sorting option in notes on my iphone

    i am using iPhone & i want to sort my notes date wise ... pls help if anybody has any idea to do it...

  • Fill color color on its own

    Hi! I'm having an issue on my Illustrator CC 2014. When I double click over the Fill color box, on the tool box, to change it, it show a tottaly different color. e.g I have a green object: 85.10.100.0 I try to edit this color by doubble cliking over

  • What are normal business hours for support?

    What are normal business hours for Apple Support in the Hong Kong region? The support page at: http://www.apple.com/hk/en/support/iphone/contact/ and the phone number, when called, do not specify normal business hours.  In fact, the phone number, whe

  • Re: Razr M - Comments, Tips or Complaints

    I am just looking for little feedback on the New Razr M. Any comments, tip or tricks learned from or about setup, and of course complaints.

  • Corner Widget is imperfect

    Not to quote Nomad here, but my investigation of the corner widget reveals what I feared, because it reflects the same imperfection as in InDesign with its rounded corner feature. Making a rounded corner with just about any radius is fine. However, w