Insert Into Vs Insert through a Procedure

Hi All,
I want to make a comparison between insertion into a table through normal insert into staement and through a procedure.
I create a table call test_table with 6 columns and a procedure to insert in that table.
I opened a session that make normal insert for 32 times and another session that uses the procedure to insert for 39 times. My experience says that insertion through a procedure is faster than normal insert into statement. but when i make trace for both sessions here is the results:
Session1(Normal Insert)
INSERT INTO TEST_TABLE
VALUES(:"SYS_B_0", :"SYS_B_1", :"SYS_B_2", :"SYS_B_3", :"SYS_B_4", :"SYS_B_5")
call count cpu elapsed disk query current rows
Parse 32 0.00 0.00 0 0 0 0
Execute 32 0.01 0.02 0 32 129 32
Fetch 0 0.00 0.00 0 0 0 0
total 64 0.01 0.03 0 32 129 32
Misses in library cache during parse: 1
Optimizer mode: CHOOSE
Parsing user id: 125 (CALLCNTR44)
Rows Execution Plan
0 INSERT STATEMENT MODE: CHOOSE
OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 32 0.00 0.00 0 0 0 0
Execute 32 0.01 0.02 0 32 129 32
Fetch 0 0.00 0.00 0 0 0 0
total 64 0.01 0.03 0 32 129 32
Misses in library cache during parse: 1
OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 0 0.00 0.00 0 0 0 0
Fetch 0 0.00 0.00 0 0 0 0
total 0 0.00 0.00 0 0 0 0
Misses in library cache during parse: 0
32 user SQL statements in session.
0 internal SQL statements in session.
32 SQL statements in session.
1 statement EXPLAINed in this session.
Trace for Session2(Procedure Insert)
BEGIN sec1.INSERT_INTO_TEXT_TABLE (); END;
call count cpu elapsed disk query current rows
Parse 39 0.04 0.00 0 0 0 0
Execute 39 0.00 0.00 0 0 0 39
Fetch 0 0.00 0.00 0 0 0 0
total 78 0.04 0.01 0 0 0 39
Misses in library cache during parse: 1
Optimizer mode: CHOOSE
Parsing user id: 125 (CALLCNTR44)
INSERT INTO TEST_TABLE
VALUES('TEST COL1', 'TEST COL2', 'TEST COL3', 'TEST COL4', 'TEST COL5', 'TEST COL6')
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 39 0.03 0.00 0 0 80 39
Fetch 0 0.00 0.00 0 0 0 0
total 39 0.03 0.00 0 0 80 39
Misses in library cache during parse: 0
Optimizer mode: CHOOSE
Parsing user id: 474 (SEC1) (recursive depth: 1)
Rows Execution Plan
0 INSERT STATEMENT MODE: CHOOSE
OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 117 0.04 0.02 0 0 0 0
Execute 117 0.03 0.03 0 0 0 78
Fetch 39 0.03 0.00 0 312 0 0
total 273 0.10 0.06 0 312 0 78
Misses in library cache during parse: 3
OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 2 0.00 0.00 0 0 0 0
Execute 41 0.04 0.01 0 0 80 39
Fetch 2 0.00 0.00 1 5 0 2
total 45 0.04 0.02 1 5 80 41
Misses in library cache during parse: 2
118 user SQL statements in session.
2 internal SQL statements in session.
120 SQL statements in session.
1 statement EXPLAINed in this session.
So in session 2 parsing of the procedure it self is still done in each execution but for the statment inside it no and in session1 parsing for the insert is done for every execution. So does this proof my knowledge or it is wrong?
I see that instead of parsing the insert in session1 there is parsing for the procedure in session2 is that correct?
Thanks in advance

Tomy3k_Bakr, you are doing the comparison wrong. Are you running these from sqlplus over and over again? Sqlplus parses every statement you send, this is not the correct way to compare.
Try this instead.
YAS@10G>create table t (a number,b number,c number);
Table created.
YAS@10G>r
  1  create or replace procedure insert_t(pa number,pb number,pc number) as
  2  begin
  3     insert into t values(pa,pb,pc);
  4* end;
Procedure created.Run this and see the results.
exec RUNSTATS_PKG.rs_start;
begin
for i in 1..10000 loop
     insert /*+ sql */ into t values(i,i,i);
end loop;
end;
exec RUNSTATS_PKG.rs_middle;
begin
for i in 1..10000 loop
     insert_t(i,i,i);
end loop;
end;
exec RUNSTATS_PKG.rs_stop;
Run1 ran in 124 hsecs
Run2 ran in 139 hsecs
run 1 ran in 89.21% of the time
Name                                  Run1        Run2        Diff
LATCH.list of block allocation           1           0          -1
STAT...redo ordering marks              92          91          -1
STAT...table scans (short tabl           3           2          -1
LATCH.session idle bit                  27          26          -1
LATCH.In memory undo latch               0           1           1
LATCH.file cache latch                   3           2          -1
LATCH.redo allocation                    8           7          -1
LATCH.archive process latch              1           0          -1
LATCH.Consistent RBA                     2           3           1
LATCH.lgwr LWN SCN                       3           2          -1
LATCH.mostly latch-free SCN              3           2          -1
LATCH.KMG MMAN ready and start           1           0          -1
LATCH.compile environment latc           3           2          -1
LATCH.session timer                      0           1           1
LATCH.shared pool                        2           3           1
STAT...change write time                11          12           1
STAT...table scan blocks gotte           6           4          -2
STAT...messages sent                     2           4           2
STAT...data blocks consistent            3           1          -2
LATCH.channel operations paren           8           6          -2
STAT...rollbacks only - consis           3           1          -2
STAT...cleanout - number of kt          27          31           4
STAT...index fetch by key                6           2          -4
STAT...cluster key scans                 6           2          -4
STAT...active txn count during          27          31           4
STAT...deferred (CURRENT) bloc           6           2          -4
STAT...consistent changes               20          24           4
STAT...consistent gets - exami          39          35          -4
STAT...session cursor cache hi          11           7          -4
STAT...CR blocks created                 6           2          -4
STAT...commit cleanouts succes           6           2          -4
STAT...commit cleanouts                  6           2          -4
STAT...workarea memory allocat           5           1          -4
STAT...calls to kcmgcs                  27          31           4
STAT...execute count                10,014      10,009          -5
LATCH.active checkpoint queue            5           0          -5
STAT...opened cursors cumulati          14           8          -6
STAT...db block changes             20,324      20,318          -6
LATCH.redo writing                      14           8          -6
STAT...parse count (total)              14           8          -6
STAT...CPU used when call star         131         138           7
STAT...calls to kcmgas                 101          94          -7
LATCH.undo global data                  50          43          -7
STAT...no work - consistent re          15           7          -8
LATCH.dml lock allocation               12           4          -8
STAT...DB time                         132         140           8
STAT...cluster key scan block           12           4          -8
LATCH.library cache lock                16           8          -8
STAT...buffer is not pinned co          12           4          -8
LATCH.messages                          27          17         -10
STAT...db block gets from cach      10,484      10,473         -11
STAT...db block gets                10,484      10,473         -11
STAT...enqueue releases                 24          13         -11
STAT...enqueue requests                 24          13         -11
STAT...recursive cpu usage              96         107          11
STAT...Elapsed Time                    127         140          13
LATCH.enqueues                          35          22         -13
STAT...redo entries                 10,181      10,195          14
STAT...CPU used by this sessio         124         138          14
LATCH.library cache pin             20,072      20,056         -16
LATCH.cache buffers lru chain          135         153          18
STAT...table scan rows gotten           54          36         -18
STAT...calls to get snapshot s          37          19         -18
LATCH.library cache                 20,094      20,073         -21
LATCH.enqueue hash chains               50          26         -24
STAT...bytes received via SQL*       1,210       1,185         -25
STAT...consistent gets                  91          63         -28
STAT...consistent gets from ca          91          63         -28
STAT...free buffer requested           118         152          34
STAT...session logical reads        10,575      10,536         -39
LATCH.row cache objects                153         106         -47
LATCH.checkpoint queue latch            57           0         -57
LATCH.SQL memory manager worka          73           6         -67
LATCH.cache buffer handles              16          84          68
STAT...recursive calls              10,132      10,053         -79
LATCH.object queue header oper         334         437         103
LATCH.cache buffers chains          51,652      51,526        -126
LATCH.session allocation               258         104        -154
STAT...free buffer inspected           448         188        -260
LATCH.simulator lru latch              440         865         425
LATCH.simulator hash latch             458         892         434
STAT...hot buffers moved to he       1,222         276        -946
STAT...undo change vector size     684,064     682,932      -1,132
STAT...redo size                 2,586,108   2,583,908      -2,200
Run1 latches total versus runs -- difference and pct
Run1        Run2        Diff       Pct
94,017      94,489         472     99.50%For runstats see http://asktom.oracle.com/tkyte/runstats.html.

Similar Messages

  • Record not inserting into the table through Forms 10g

    Hi all,
    I have created a form in 10g(10.1.2.0.2) based on just one table that has 4 columns(col1, col2, col3, col4).
    Here col1, col2 and col3 are VARCHAR2 and col4 is date and all the columns are not null columns(There are no primary and foriegn key constrains, which means duplicates are allowed).
    My form contains 2 blocks where block 1 has one text item (col1) and 3 buttons (Delete, Save, Exit).
    And block2 is a database block and has col2,col3,col4 which are in tabluar layout frame displaying 10 records.
    When the form is opened the cursor has to be in block1.col1 for querrying. Here i enter a value in col1, and then when I click on col2 in the block2, then I put execute_query in new_block_instance of block2, which displays the records.
    The block2 properties are not updatable, insertable and query is allowed.
    Everything is working good until here. But here in the block2 when I want to insert another record into the table, by navigating all the way down to the last empty record and entering the new values for col2, col3 and col4 And then Ctrl+S will display the message "*FRM-40400: Transaction complete: 1 record applied and saved.*" But actually the record is not inserted into the table.
    I also disabled the col4 by setting the Enabled property to No, since while inserting new record the date have to be populated into it and it shouldnt be changed by the user. And im populating the sysdate into the new record by setting Intial Value property to *$$DATE$$*.
    And another requirement which I could not work arround here is that, the col3 also should be populated with the username of the user while inserting.
    please help me...

    Hi Sarah,
    I do not want to update the existing record. So I kept Udate Allowed to No in property palette for the items in block2.
    Do I have to do this property at block level also?
    I'm inserting a new record here.
    Edited by: Charan on Sep 19, 2011 8:48 AM

  • Error while inserting into blob column through PL/SQL

    Hi All,
    I am trying to insert into column having blob as datatype.
    INSERT INTO imagedb(image_name, content,description) VALUES ('logo.png',
    ?{file 'c:\logo.png'}, 'logo');
    it gives me error Unknown JDBC escape sequence:
    Is there anything wrong in above insert syntax for inserting into BLOB data type.
    Can any body please help me.
    Regards,
    Hiren

    It is not valid SQL as far as Oracle SQL is concerned. I assume that the file construct is suppose to replace that with the contents of the file?
    What happens when the file size exceeds the max length of the SQL command?
    And do you have any idea what will happen to the SQL Shared Pool on Oracle that needs to store the entire SQL command for every single SQL command passed to it? The whole purpose of the Shared Pool is for storing shared SQL. Not non-sharable SQL containing hardcoded values.
    Bind variable are to be used.. if you expect Oracle to perform like only Oracle can.
    And my bet is that you have not even bothered to read [url http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14249/toc.htm]Oracle® Database Application Developer's Guide - Large Objects guide....

  • How to insert into a table using a procedure in a trigger

    I have following trigger and based on the some condition, it should inser a row in to a table using the procedure:
    CREATE OR REPLACE TRIGGER RSSC.RR_SERV_ADD_ON_REQ_bu before update on RSSC.RR_SERV_ADD_ON_REQ
    for each row
    DECLARE
    lr_appr_trans_hdr APPR_TRANS_HDR%ROWTYPE;
    -- Inserting a row into APPR_TRANS_HDR table
              lr_appr_trans_hdr.apth_ref_system := 'RSAO';
              lr_appr_trans_hdr.apth_xref_col_name := 'RSAO_ADD_ON_REQ_NUM';
              lr_appr_trans_hdr.apth_xref_id := :NEW.RSAO_ADD_ON_REQ_NUM;
              lr_appr_trans_hdr.apth_trans_srce := 'I';
              lr_appr_trans_hdr.apth_balance_amt := :NEW.RSAO_TOT_AMT;
              lr_appr_trans_hdr.apth_is_finance_adj := 'N';
              SPI_APPR_TRANS_HDR (
              lr_appr_trans_hdr.apth_id
              ,lr_appr_trans_hdr.apth_create_dt
                   ,lr_appr_trans_hdr.apth_create_user_id
                   ,lr_appr_trans_hdr.apth_update_dt
                   ,lr_appr_trans_hdr.apth_update_user_id
              ,lr_appr_trans_hdr.apth_ref_system
                   ,lr_appr_trans_hdr.apth_xref_col_name
                   ,lr_appr_trans_hdr.apth_xref_id
                   ,lr_appr_trans_hdr.apth_trans_srce
                   ,lr_appr_trans_hdr.apth_udc_name_cd
                   ,lr_appr_trans_hdr.apth_udc_acct_num
                   ,lr_appr_trans_hdr.apth_level1_apprvl_stat
                   ,lr_appr_trans_hdr.apth_level1_apprvl_dt
                   ,lr_appr_trans_hdr.apth_level1_apprvr_id
                   ,lr_appr_trans_hdr.apth_level2_apprvl_stat
                   ,lr_appr_trans_hdr.apth_level2_apprvl_dt
                   ,lr_appr_trans_hdr.apth_level2_apprvr_id
                   ,lr_appr_trans_hdr.apth_received_dt
                   ,lr_appr_trans_hdr.apth_balance_amt
                   ,lr_appr_trans_hdr.apth_cust_name
                   ,lr_appr_trans_hdr.apth_sent_dt
                   ,lr_appr_trans_hdr.apth_wbs_element
                   ,lr_appr_trans_hdr.apth_gl_acct_num
                   ,lr_appr_trans_hdr.apth_is_finance_adj );
    When I use the above, it is saying wrong number of argument or type.
    When I use the following instead, I am getting :NEW.APTH_ID must be declared.
    SPI_APPR_TRANS_HDR('APPR_TRANS_HDR',to_char(:NEW.APTH_ID),'APTH_ID',:OLD.APTH_ID,:NEW.APTH_ID);
    How can use the procedure in a trigger.
    Following is the table structure:
    Column Name     Data Type     Column Comments
    APTH_ID     NUMBER(16) Computed unique identified per large table standards (yyyymmddnnnnnnnn)
    APTH_CREATE_DT     DATE     sysdate
    APTH_CREATE_USER_ID VARCHAR2(65)     ‘conv’
    APTH_UPDATE_DT     DATE     sysdate
    APTH_UPDATE_USER_ID     VARCHAR2(65)     ‘conv’
    APTH_REF_SYSTEM     VARCHAR2(4)     ‘RSAO’
    CPA_PREM_NUM     NUMBER(13,0)     NULL
    RSR_REQ_NUM     NUMBER(16)     NULL
    RSAO_ADD_ON_REQ_NUM     NUMBER(16)     rsao_add_on_req_num
    APTH_TRANS_SRCE     VARCHAR2(2)     ‘I’
    APTH_LDC_NAME_CD     VARCHAR2(4)     NULL
    APTH_LDC_ACCT_NUM     VARCHAR2(25)     NULL
    APTH_LEVEL1_APPROVAL_STAT     VARCHAR2(1)     NULL
    APTH_LEVEL1_APPROVAL_DT     DATE     NULL.
    APTH_LEVEL1_APPROVAL_ID     VARCHAR2(30)     NULL
    APTH_LEVEL2_APPROVAL_STAT     VARCHAR2(1)     NULL
    APTH_LEVEL2_APPROVAL_DT     DATE     NULL.
    APTH_LEVEL2_APPROVAL_ID     VARCHAR2(30)     NULL
    APTH_RECEIVED_DT     DATE     NULL
    APTH_BALANCE_AMT     NUMBER(11,2) RR_SERV_ADD_ON_REQ.rsao_tot_amt – amount previously extracted to sap
    APTH_CUST_NAME     VARCHAR2(65)     NULL
    APTH_SENT_DT     DATE     NULL
    APTH_WBS_ELEMENT     VARCHAR2(25)     NULL
    APTH_GL_ACCT_NUM     VARCHAR2(15) NULL
    APTH_IS_FINANC_ADJ     VARCHAR2(1)     ‘N’
    Edited by: user652807 on Sep 3, 2008 4:51 PM

    It appears you're missing the format mask in the TO_CHAR, ...
    TO_CHAR(:new.apth,'YYYYMMHR24MISS')
    The full code would help a bit more.

  • Insert into tables in different schemas

    hi,
    I insert into few tables through stored procedures, now there is a scenario wherein,
    by passing parameters to the stored procedures i should be able to insert into table in another schema.
    Eg.,
    Table EMP in Schema Dev
    Table EMP in Schema Test
    MY stored procedures should insert into dev's emp or Test's EMP table based on the parameter.
    The procedures are combined as a package and will be run through CONTROL M scheduler with the help of environment files.
    Thanks in advance

    A) Double your procedures/packages and let Control-M run it in Test and in Production environment.
    B) Avoid dynamical calls. This will usually create problems later on. E.g. if column ename is dropped from table emp, your package will not invalidate. Furthermore each dynamic SQL has a potential risk for code injection if not used with binding. Imagine somebode calls this with v_schema = ' dual values (''hacked db''); insert into test'
    C) There is some ALTER SESSION command to switch the current schema. Maybe this helps.

  • Inserting & symbol to table through procedure

    I want to insert a data with & symbol into a table through the procedure.
    Is it possible.
    through the console i put set define off. it works fine on console.
    but in plsql i am unable to use set commands since it is a console command.
    please advice.

    Hi,
    '&' is a special symbol for SQL*Plus only. It's an ordinary character in PL/SQL.
    SQL> create table test_data(s varchar2(200));
    Table created.
    SQL> set define off
    SQL> create or replace procedure p as
      2  begin
      3    insert into test_data values('&');
      4    insert into test_data values('&&');
      5    insert into test_data values('&fff&&&');
      6    commit;
      7  end;
      8  /
    Procedure created.
    SQL>
    SQL> set define on
    SQL> exec p;
    PL/SQL procedure successfully completed.
    SQL> select * from test_data;
    S
    &fff&&&Regards,
    Dima

  • Inserting into table..!

    Hi,
    I got a database table with a Cloumn,and i have created sequence on that column.
    I would like to insert into that table through my JSP program.
    Do i need to lock my table exclusively?
    What happens if two different users try to insert into the same table at the same time through my JSP program?(Iam already using
    setAutocommit(off/on) in my JSP program before/after the Insert statement).
    Or does the webserver/Oracle has got any automatic lockiing system.
    Do i need to add any more statements in my JSP program,other than normal statements used to insert into a table(Conn,rs,stmt)?
    Thanks in advance
    Regards
    Rao.

    Three scenarios
    (1) Using a before-insert trigger to populate the PK with sequence.nextval. Insert statement would populate non PK fields only.
    (2) Using sequence.nextval within the insert statement.
    (3) Retrieving and storing sequence.nextval for displaying to user. Later using that with the insert statement naming all the fields
    Oracle would take care of concurrency in the first two scenarios. In the third case, if the retrieval and actual insert are in different methods then together they define the atomic transaction and you have to set up the descriptor like that.
    Hope it helps!

  • Problem in Inserting the Value in the column through Stored Procedure

    stored procedure is created and i need
    to insert data into the SALES_TRADEIN, from the parent table (Flatfile_sales),through COMMAND PROMPT.
    I have 2 details TradeIn_1 and TradeIn_2.
    I need to insert details of TradeIn_1 in SALES_TRADEIN
    TABLE if the column of TradeIn_1 is null then i need to insert TradeIn_2 details.
    If the TradeIn_1 is not null then i have insert
    TradeIn_1 details and go to next column.
    This is the Scenario but i wrote the Script
    so anyone please view it and give the solution how to change that insert statement.
    -- =============================================
    -- Stored Procedure for Flatfile_Sales
    -- =============================================
    ---==========Sales_Cursor
    --USE [IconicMarketing]
    --GO
    DECLARE
    @FileType varchar(50),
    @ACDealerID varchar(50),
    @ClientDealerID varchar(50),
    @DMSType varchar(50),
    @DealNumber varchar(50),
    @CustomerNumber varchar(50),
    @CustomerName varchar(50),
    @CustomerFirstName varchar(50),
    @CustomerLastName varchar(50),
    @CustomerAddress varchar(50),
    @CustomerCity varchar(50),
    @CustomerState varchar(50),
    @CustomerZip varchar(50),
    @CustomerCounty varchar(50),
    @CustomerHomePhone varchar(50),
    @CustomerWorkPhone varchar(50),
    @CustomerCellPhone varchar(50),
    @CustomerPagerPhone varchar(50),
    @CustomerEmail varchar(50),
    @CustomerBirthDate varchar(50),
    @MailBlock varchar(50),
    @CoBuyerName varchar(50),
    @CoBuyerFirstName varchar(50),
    @CoBuyerLastName varchar(50),
    @CoBuyerAddress varchar(50),
    @CoBuyerCity varchar(50),
    @CoBuyerState varchar(50),
    @CoBuyerZip varchar(50),
    @CoBuyerCounty varchar(50),
    @CoBuyerHomePhone varchar(50),
    @CoBuyerWorkPhone varchar(50),
    @CoBuyerBirthDate varchar(50),
    @Salesman_1_Number varchar(50),
    @Salesman_1_Name varchar(50),
    @Salesman_2_Number varchar(50),
    @Salesman_2_Name varchar(50),
    @ClosingManagerName varchar(50),
    @ClosingManagerNumber varchar(50),
    @F_AND_I_ManagerNumber varchar(50),
    @F_AND_I_ManagerName varchar(50),
    @SalesManagerNumber varchar(50),
    @SalesManagerName varchar(50),
    @EntryDate varchar(50),
    @DealBookDate varchar(50),
    @VehicleYear varchar(50),
    @VehicleMake varchar(50),
    @VehicleModel varchar(50),
    @VehicleStockNumber varchar(50),
    @VehicleVIN varchar(50),
    @VehicleExteriorColor varchar(50),
    @VehicleInteriorColor varchar(50),
    @VehicleMileage varchar(50),
    @VehicleType varchar(50),
    @InServiceDate varchar(50),
    @HoldBackAmount varchar(50),
    @DealType varchar(50),
    @SaleType varchar(50),
    @BankCode varchar(50),
    @BankName varchar(50),
    @SalesmanCommission varchar(50),
    @GrossProfitSale varchar(50),
    @FinanceReserve varchar(50),
    @CreditLifePremium varchar(50),
    @CreditLifeCommision varchar(50),
    @TotalInsuranceReserve varchar(50),
    @BalloonAmount varchar(50),
    @CashPrice varchar(50),
    @AmountFinanced varchar(50),
    @TotalOfPayments varchar(50),
    @MSRP varchar(50),
    @DownPayment varchar(50),
    @SecurityDesposit varchar(50),
    @Rebate varchar(50),
    @Term varchar(50),
    @RetailPayment varchar(50),
    @PaymentType varchar(50),
    @RetailFirstPayDate varchar(50),
    @LeaseFirstPayDate varchar(50),
    @DayToFirstPayment varchar(50),
    @LeaseAnnualMiles varchar(50),
    @MileageRate varchar(50),
    @APRRate varchar(50),
    @ResidualAmount varchar(50),
    @LicenseFee varchar(50),
    @RegistrationFee varchar(50),
    @TotalTax varchar(50),
    @ExtendedWarrantyName varchar(50),
    @ExtendedWarrantyTerm varchar(50),
    @ExtendedWarrantyLimitMiles varchar(50),
    @ExtendedWarrantyDollar varchar(50),
    @ExtendedWarrantyProfit varchar(50),
    @FrontGross varchar(50),
    @BackGross varchar(50),
    @TradeIn_1_VIN varchar(50),
    @TradeIn_2_VIN varchar(50),
    @TradeIn_1_Make varchar(50),
    @TradeIn_2_Make varchar(50),
    @TradeIn_1_Model varchar(50),
    @TradeIn_2_Model varchar(50),
    @TradeIn_1_ExteriorColor varchar(50),
    @TradeIn_2_ExteriorColor varchar(50),
    @TradeIn_1_Year varchar(50),
    @TradeIn_2_Year varchar(50),
    @TradeIn_1_Mileage varchar(50),
    @TradeIn_2_Mileage varchar(50),
    @TradeIn_1_Gross varchar(50),
    @TradeIn_2_Gross varchar(50),
    @TradeIn_1_Payoff varchar(50),
    @TradeIn_2_Payoff varchar(50),
    @TradeIn_1_ACV varchar(50),
    @TradeIn_2_ACV varchar(50),
    @Fee_1_Name varchar(50),
    @Fee_1_Fee varchar(50),
    @Fee_1_Commission varchar(50),
    @Fee_2_Name varchar(50),
    @Fee_2_Fee varchar(50),
    @Fee_2_Commission varchar(50),
    @Fee_3_Name varchar(50),
    @Fee_3_Fee varchar(50),
    @Fee_3_Commission varchar(50),
    @Fee_4_Name varchar(50),
    @Fee_4_Fee varchar(50),
    @Fee_4_Commission varchar(50),
    @Fee_5_Name varchar(50),
    @Fee_5_Fee varchar(50),
    @Fee_5_Commission varchar(50),
    @Fee_6_Name varchar(50),
    @Fee_6_Fee varchar(50),
    @Fee_6_Commission varchar(50),
    @Fee_7_Name varchar(50),
    @Fee_7_Fee varchar(50),
    @Fee_7_Commission varchar(50),
    @Fee_8_Name varchar(50),
    @Fee_8_Fee varchar(50),
    @Fee_8_Commission varchar(50),
    @Fee_9_Name varchar(50),
    @Fee_9_Fee varchar(50),
    @Fee_9_Commission varchar(50),
    @Fee_10_Name varchar(50),
    @Fee_10_Fee varchar(50),
    @Fee_10_Commission varchar(50),
    @ContractDate varchar(50),
    @InsuranceName varchar(50),
    @InsuranceAgentName varchar(50),
    @InsuranceAddress varchar(50),
    @InsuranceCity varchar(50),
    @InsuranceState varchar(50),
    @InsuranceZip varchar(50),
    @InsurancePhone varchar(50),
    @InsurancePolicyNumber varchar(50),
    @InsuranceEffectiveDate varchar(50),
    @InsuranceExpirationDate varchar(50),
    @InsuranceCompensationDeduction varchar(50),
    @TradeIn_1_InteriorColor varchar(50),
    @TradeIn_2_InteriorColor varchar(50),
    @PhoneBlock varchar(50),
    @LicensePlateNumber varchar(50),
    @Cost varchar(50),
    @InvoiceAmount varchar(50),
    @FinanceCharge varchar(50),
    @TotalPickupPayment varchar(50),
    @TotalAccessories varchar(50),
    @TotalDriveOffAmount varchar(50),
    @EmailBlock varchar(50),
    @ModelDescriptionOfCarSold varchar(50),
    @VehicleClassification varchar(50),
    @ModelNumberOfCarSold varchar(50),
    @GAPPremium varchar(50),
    @LastInstallmentDate varchar(50),
    @CashDeposit varchar(50),
    @AHPremium varchar(50),
    @LeaseRate varchar(50),
    @DealerSelect varchar(50),
    @LeasePayment varchar(50),
    @LeaseNetCapCost varchar(50),
    @LeaseTotalCapReduction varchar(50),
    @DealStatus varchar(50),
    @CustomerSuffix varchar(50),
    @CustomerSalutation varchar(50),
    @CustomerAddress2 varchar(50),
    @CustomerMiddleName varchar(50),
    @GlobalOptOut varchar(50),
    @LeaseTerm varchar(50),
    @ExtendedWarrantyFlag varchar(50),
    @Salesman_3_Number varchar(50),
    @Salesman_3_Name varchar(50),
    @Salesman_4_Number varchar(50),
    @Salesman_4_Name varchar(50),
    @Salesman_5_Number varchar(50),
    @Salesman_5_Name varchar(50),
    @Salesman_6_Number varchar(50),
    @Salesman_6_Name varchar(50),
    @APRRate2 varchar(50),
    @APRRate3 varchar(50),
    @APRRate4 varchar(50),
    @Term2 varchar(50),
    @SecurityDeposit2 varchar(50),
    @DownPayment2 varchar(50),
    @TotalOfPayments2 varchar(50),
    @BasePayment varchar(50),
    @JournalSaleAmount varchar(50),
    @IndividualBusinessFlag varchar(50),
    @InventoryDate varchar(50),
    @StatusDate varchar(50),
    @ListPrice varchar(50),
    @NetTradeAmount varchar(50),
    @TrimLevel varchar(50),
    @SubTrimLevel varchar(50),
    @BodyDescription varchar(50),
    @BodyDoorCount varchar(50),
    @TransmissionDesc varchar(50),
    @EngineDesc varchar(50),
    @TypeCode varchar(50),
    @SLCT2 varchar(50),
    @DealDateOffset varchar(50),
    @AccountingDate varchar(50),
    @CoBuyerCustNum varchar(50),
    @CoBuyerCell varchar(50),
    @CoBuyerEmail varchar(50),
    @CoBuyerSalutation varchar(50),
    @CoBuyerPhoneBlock varchar(50),
    @CoBuyerMailBlock varchar(50),
    @CoBuyerEmailBlock varchar(50),
    @RealBookDate varchar(50),
    @CoBuyerMiddleName varchar(50),
    @CoBuyerCountry varchar(50),
    @CoBuyerAddress2 varchar(50),
    @CoBuyerOptOut varchar(50),
    @CoBuyerOccupation varchar(50),
    @CoBuyerEmployer varchar(50),
    @Country varchar(50),
    @Occupation varchar(50),
    @Employer varchar(50),
    @Salesman2Commission varchar(50),
    @BankAddress varchar(50),
    @BankCity varchar(50),
    @BankState varchar(50),
    @BankZip varchar(50),
    @LeaseEstimatedMiles varchar(50),
    @AFTReserve varchar(50),
    @CreditLifePrem varchar(50),
    @CreditLifeRes varchar(50),
    @AHRes varchar(50),
    @Language varchar(50),
    @BuyRate varchar(50),
    @DMVAmount varchar(50),
    @Weight varchar(50),
    @StateDMVTotFee varchar(50),
    @ROSNumber varchar(50),
    @Incentives varchar(50),
    @CASS_STD_LINE1 varchar(50),
    @CASS_STD_LINE2 varchar(50),
    @CASS_STD_CITY varchar(50),
    @CASS_STD_STATE varchar(50),
    @CASS_STD_ZIP varchar(50),
    @CASS_STD_ZIP4 varchar(50),
    @CASS_STD_DPBC varchar(50),
    @CASS_STD_CHKDGT varchar(50),
    @CASS_STD_CART varchar(50),
    @CASS_STD_LOT varchar(50),
    @CASS_STD_LOTORD varchar(50),
    @CASS_STD_URB varchar(50),
    @CASS_STD_FIPS varchar(50),
    @CASS_STD_EWS varchar(50),
    @CASS_STD_LACS varchar(50),
    @CASS_STD_ZIPMOV varchar(50),
    @CASS_STD_Z4LOM varchar(50),
    @CASS_STD_NDIAPT varchar(50),
    @CASS_STD_NDIRR varchar(50),
    @CASS_STD_LACSRT varchar(50),
    @CASS_STD_ERROR_CD varchar(50),
    @NCOA_AC_ID varchar(50),
    @NCOA_COA_ADDSRC varchar(50),
    @NCOA_COA_MATCH varchar(50),
    @NCOA_COA_MOVTYP varchar(50),
    @NCOA_COA_DATE varchar(50),
    @NCOA_COA_DELCD varchar(50),
    @NCOA_COA_RTYPE varchar(50),
    @NCOA_COA_RTNCD varchar(50),
    @NCOA_COA_LINE1 varchar(50),
    @NCOA_COA_LINE2 varchar(50),
    @NCOA_COA_CITY varchar(50),
    @NCOA_COA_STATE varchar(50),
    @NCOA_COA_ZIP varchar(50),
    @NCOA_COA_ZIP4 varchar(50),
    @NCOA_COA_DPBC varchar(50),
    @NCOA_COA_CHKDGT varchar(50),
    @NCOA_COA_CART varchar(50),
    @NCOA_COA_LOT varchar(50),
    @NCOA_COA_LOTORD varchar(50),
    @NCOA_COA_URB varchar(50),
    @NCOA_COA_Z4LOM varchar(50),
    @NCOA_COA_ACTION varchar(50),
    @NCOA_COA_QNAME varchar(50),
    @NCOA_DPV_AA varchar(50),
    @NCOA_DPV_A1 varchar(50),
    @NCOA_DPV_BB varchar(50),
    @NCOA_DPV_CC varchar(50),
    @NCOA_DPV_M1 varchar(50),
    @NCOA_DPV_M3 varchar(50),
    @NCOA_DPV_N1 varchar(50),
    @NCOA_DPV_P1 varchar(50),
    @NCOA_DPV_P3 varchar(50),
    @NCOA_DPV_RR varchar(50),
    @NCOA_DPV_R1 varchar(50),
    @NCOA_DPV_STATUS varchar(50),
    @NCOA_DPV_F1 varchar(50),
    @NCOA_DPV_G1 varchar(50),
    @NCOA_DPV_U1 varchar(50),
    @SalesID int;
    DECLARE Sales_Cursor CURSOR FOR
    SELECT * from FLATFILE_SALES;
    OPEN Sales_Cursor
    FETCH NEXT FROM Sales_Cursor
    INTO @FileType ,
    @ACDealerID ,
    @ClientDealerID ,
    @DMSType ,
    @DealNumber ,
    @CustomerNumber ,
    @CustomerName ,
    @CustomerFirstName ,
    @CustomerLastName ,
    @CustomerAddress ,
    @CustomerCity ,
    @CustomerState ,
    @CustomerZip ,
    @CustomerCounty ,
    @CustomerHomePhone ,
    @CustomerWorkPhone ,
    @CustomerCellPhone ,
    @CustomerPagerPhone ,
    @CustomerEmail ,
    @CustomerBirthDate ,
    @MailBlock ,
    @CoBuyerName ,
    @CoBuyerFirstName ,
    @CoBuyerLastName ,
    @CoBuyerAddress ,
    @CoBuyerCity ,
    @CoBuyerState ,
    @CoBuyerZip ,
    @CoBuyerCounty ,
    @CoBuyerHomePhone ,
    @CoBuyerWorkPhone ,
    @CoBuyerBirthDate ,
    @Salesman_1_Number ,
    @Salesman_1_Name ,
    @Salesman_2_Number ,
    @Salesman_2_Name ,
    @ClosingManagerName ,
    @ClosingManagerNumber ,
    @F_AND_I_ManagerNumber ,
    @F_AND_I_ManagerName ,
    @SalesManagerNumber ,
    @SalesManagerName ,
    @EntryDate ,
    @DealBookDate ,
    @VehicleYear ,
    @VehicleMake ,
    @VehicleModel ,
    @VehicleStockNumber ,
    @VehicleVIN ,
    @VehicleExteriorColor ,
    @VehicleInteriorColor ,
    @VehicleMileage ,
    @VehicleType ,
    @InServiceDate ,
    @HoldBackAmount ,
    @DealType ,
    @SaleType ,
    @BankCode ,
    @BankName ,
    @SalesmanCommission ,
    @GrossProfitSale ,
    @FinanceReserve ,
    @CreditLifePremium ,
    @CreditLifeCommision ,
    @TotalInsuranceReserve ,
    @BalloonAmount ,
    @CashPrice ,
    @AmountFinanced ,
    @TotalOfPayments ,
    @MSRP ,
    @DownPayment ,
    @SecurityDesposit ,
    @Rebate ,
    @Term ,
    @RetailPayment ,
    @PaymentType ,
    @RetailFirstPayDate ,
    @LeaseFirstPayDate ,
    @DayToFirstPayment ,
    @LeaseAnnualMiles ,
    @MileageRate ,
    @APRRate ,
    @ResidualAmount ,
    @LicenseFee ,
    @RegistrationFee ,
    @TotalTax ,
    @ExtendedWarrantyName ,
    @ExtendedWarrantyTerm ,
    @ExtendedWarrantyLimitMiles ,
    @ExtendedWarrantyDollar ,
    @ExtendedWarrantyProfit ,
    @FrontGross ,
    @BackGross ,
    @TradeIn_1_VIN ,
    @TradeIn_2_VIN ,
    @TradeIn_1_Make ,
    @TradeIn_2_Make ,
    @TradeIn_1_Model ,
    @TradeIn_2_Model ,
    @TradeIn_1_ExteriorColor ,
    @TradeIn_2_ExteriorColor ,
    @TradeIn_1_Year ,
    @TradeIn_2_Year ,
    @TradeIn_1_Mileage ,
    @TradeIn_2_Mileage ,
    @TradeIn_1_Gross ,
    @TradeIn_2_Gross ,
    @TradeIn_1_Payoff ,
    @TradeIn_2_Payoff ,
    @TradeIn_1_ACV ,
    @TradeIn_2_ACV ,
    @Fee_1_Name ,
    @Fee_1_Fee ,
    @Fee_1_Commission ,
    @Fee_2_Name ,
    @Fee_2_Fee ,
    @Fee_2_Commission ,
    @Fee_3_Name ,
    @Fee_3_Fee ,
    @Fee_3_Commission ,
    @Fee_4_Name ,
    @Fee_4_Fee ,
    @Fee_4_Commission ,
    @Fee_5_Name ,
    @Fee_5_Fee ,
    @Fee_5_Commission ,
    @Fee_6_Name ,
    @Fee_6_Fee ,
    @Fee_6_Commission ,
    @Fee_7_Name ,
    @Fee_7_Fee ,
    @Fee_7_Commission ,
    @Fee_8_Name ,
    @Fee_8_Fee ,
    @Fee_8_Commission ,
    @Fee_9_Name ,
    @Fee_9_Fee ,
    @Fee_9_Commission ,
    @Fee_10_Name ,
    @Fee_10_Fee ,
    @Fee_10_Commission ,
    @ContractDate ,
    @InsuranceName ,
    @InsuranceAgentName ,
    @InsuranceAddress ,
    @InsuranceCity ,
    @InsuranceState ,
    @InsuranceZip ,
    @InsurancePhone ,
    @InsurancePolicyNumber ,
    @InsuranceEffectiveDate ,
    @InsuranceExpirationDate ,
    @InsuranceCompensationDeduction ,
    @TradeIn_1_InteriorColor ,
    @TradeIn_2_InteriorColor ,
    @PhoneBlock ,
    @LicensePlateNumber ,
    @Cost ,
    @InvoiceAmount ,
    @FinanceCharge ,
    @TotalPickupPayment ,
    @TotalAccessories ,
    @TotalDriveOffAmount ,
    @EmailBlock ,
    @ModelDescriptionOfCarSold ,
    @VehicleClassification ,
    @ModelNumberOfCarSold ,
    @GAPPremium ,
    @LastInstallmentDate ,
    @CashDeposit ,
    @AHPremium ,
    @LeaseRate ,
    @DealerSelect ,
    @LeasePayment ,
    @LeaseNetCapCost ,
    @LeaseTotalCapReduction ,
    @DealStatus ,
    @CustomerSuffix ,
    @CustomerSalutation ,
    @CustomerAddress2 ,
    @CustomerMiddleName ,
    @GlobalOptOut ,
    @LeaseTerm ,
    @ExtendedWarrantyFlag ,
    @Salesman_3_Number ,
    @Salesman_3_Name ,
    @Salesman_4_Number ,
    @Salesman_4_Name ,
    @Salesman_5_Number ,
    @Salesman_5_Name ,
    @Salesman_6_Number ,
    @Salesman_6_Name ,
    @APRRate2 ,
    @APRRate3 ,
    @APRRate4 ,
    @Term2 ,
    @SecurityDeposit2 ,
    @DownPayment2 ,
    @TotalOfPayments2 ,
    @BasePayment ,
    @JournalSaleAmount ,
    @IndividualBusinessFlag ,
    @InventoryDate ,
    @StatusDate ,
    @ListPrice ,
    @NetTradeAmount ,
    @TrimLevel ,
    @SubTrimLevel ,
    @BodyDescription ,
    @BodyDoorCount ,
    @TransmissionDesc ,
    @EngineDesc ,
    @TypeCode ,
    @SLCT2 ,
    @DealDateOffset ,
    @AccountingDate ,
    @CoBuyerCustNum ,
    @CoBuyerCell ,
    @CoBuyerEmail ,
    @CoBuyerSalutation ,
    @CoBuyerPhoneBlock ,
    @CoBuyerMailBlock ,
    @CoBuyerEmailBlock ,
    @RealBookDate ,
    @CoBuyerMiddleName ,
    @CoBuyerCountry ,
    @CoBuyerAddress2 ,
    @CoBuyerOptOut ,
    @CoBuyerOccupation ,
    @CoBuyerEmployer ,
    @Country ,
    @Occupation ,
    @Employer ,
    @Salesman2Commission ,
    @BankAddress ,
    @BankCity ,
    @BankState ,
    @BankZip ,
    @LeaseEstimatedMiles ,
    @AFTReserve ,
    @CreditLifePrem ,
    @CreditLifeRes ,
    @AHRes ,
    @Language ,
    @BuyRate ,
    @DMVAmount ,
    @Weight ,
    @StateDMVTotFee ,
    @ROSNumber ,
    @Incentives ,
    @CASS_STD_LINE1 ,
    @CASS_STD_LINE2 ,
    @CASS_STD_CITY ,
    @CASS_STD_STATE ,
    @CASS_STD_ZIP ,
    @CASS_STD_ZIP4 ,
    @CASS_STD_DPBC ,
    @CASS_STD_CHKDGT ,
    @CASS_STD_CART ,
    @CASS_STD_LOT ,
    @CASS_STD_LOTORD ,
    @CASS_STD_URB ,
    @CASS_STD_FIPS ,
    @CASS_STD_EWS ,
    @CASS_STD_LACS ,
    @CASS_STD_ZIPMOV ,
    @CASS_STD_Z4LOM ,
    @CASS_STD_NDIAPT ,
    @CASS_STD_NDIRR ,
    @CASS_STD_LACSRT ,
    @CASS_STD_ERROR_CD ,
    @NCOA_AC_ID ,
    @NCOA_COA_ADDSRC ,
    @NCOA_COA_MATCH ,
    @NCOA_COA_MOVTYP ,
    @NCOA_COA_DATE ,
    @NCOA_COA_DELCD ,
    @NCOA_COA_RTYPE ,
    @NCOA_COA_RTNCD ,
    @NCOA_COA_LINE1 ,
    @NCOA_COA_LINE2 ,
    @NCOA_COA_CITY ,
    @NCOA_COA_STATE ,
    @NCOA_COA_ZIP ,
    @NCOA_COA_ZIP4 ,
    @NCOA_COA_DPBC ,
    @NCOA_COA_CHKDGT ,
    @NCOA_COA_CART ,
    @NCOA_COA_LOT ,
    @NCOA_COA_LOTORD ,
    @NCOA_COA_URB ,
    @NCOA_COA_Z4LOM ,
    @NCOA_COA_ACTION ,
    @NCOA_COA_QNAME ,
    @NCOA_DPV_AA ,
    @NCOA_DPV_A1 ,
    @NCOA_DPV_BB ,
    @NCOA_DPV_CC ,
    @NCOA_DPV_M1 ,
    @NCOA_DPV_M3 ,
    @NCOA_DPV_N1 ,
    @NCOA_DPV_P1 ,
    @NCOA_DPV_P3 ,
    @NCOA_DPV_RR ,
    @NCOA_DPV_R1 ,
    @NCOA_DPV_STATUS ,
    @NCOA_DPV_F1 ,
    @NCOA_DPV_G1 ,
    @NCOA_DPV_U1 ;
    WHILE @@FETCH_STATUS = 0
    BEGIN
    PRINT @VehicleVIN ;
    --===============================================================================
    -- ****************** insert into Sales Table ***********
    INSERT INTO Sales
    IconicDealerID,
    DealNumber,
    CustomerNumber,
    DMSType,
    ContractDate
    VALUES (@ClientDealerID,@DealNumber,@CustomerNumber,@DMSType,@ContractDate);
    set @SalesID = scope_identity();
    PRINT @SalesID;
    --================================================================================
    --Insert into SALES_TRADEIN Table
    INSERT INTO SALES_TRADEIN
    SalesID,
    TradeIn_VIN,
    TradeIn_Make,
    TradeIn_Model,
    TradeIn_ExteriorColor,
    TradeIn_Year,
    TradeIn_Mileage,
    TradeIn_Gross,
    TradeIn_Payoff,
    TradeIn_ACV,
    TradeIn_InteriorColor
    VALUES (
    @SalesID,
    case when @TradeIn_1_VIN null then @TradeIn_1_VIN else @TradeIn_2_VIN end,
    case when @TradeIn_1_Make is null then @TradeIn_1_Make else @TradeIn_2_Make end,
    case when @TradeIn_1_Model is null then @TradeIn_1_Model else @TradeIn_2_Model end,
    case when @TradeIn_1_ExteriorColor is null then @TradeIn_1_ExteriorColor else @TradeIn_2_ExteriorColor end,
    case when @TradeIn_1_Year is null then @TradeIn_1_Year else @TradeIn_2_Year end,
    case when @TradeIn_1_Mileage is null then @TradeIn_1_Mileage else @TradeIn_2_Mileage end,
    case when @TradeIn_1_Gross is null then @TradeIn_1_Gross else @TradeIn_2_Gross end,
    case when @TradeIn_1_Payoff is not null then @TradeIn_1_Payoff else @TradeIn_2_Payoff end,
    case when @TradeIn_1_ACV is null then @TradeIn_1_ACV else @TradeIn_2_ACV end,
    case when @TradeIn_1_InteriorColor is null then @TradeIn_1_InteriorColor else @TradeIn_1_InteriorColor end
    --===============================================================================
    --Insert into SALES_VEHICLE Table
    INSERT INTO SALES_VEHICLE
    SalesID ,
    VehicleYear ,
    VehicleMake ,
    VehicleModel ,
    VehicleStockNumber ,
    VehicleVIN ,
    VehicleExteriorColor ,
    VehicleInteriorColor ,
    VehicleMileage ,
    VehicleType ,
    InServiceDate ,
    LeaseAnnualMiles ,
    ExtendedWarrantyName ,
    ExtendedWarrantyTerm ,
    ExtendedWarrantyLimitMiles ,
    LicensePlateNumber ,
    ModelDescriptionOfCarSold ,
    VehicleClassification ,
    ModelNumberOfCarSold ,
    ExtendedWarrantyFlag ,
    TrimLevel ,
    SubTrimLevel ,
    BodyDescription ,
    BodyDoorCount ,
    TransmissionDesc ,
    EngineDesc ,
    TypeCode ,
    Weight ,
    LeaseEstimatedMiles
    VALUES (
    @SalesID,@VehicleYear,@VehicleMake,@VehicleModel,@VehicleStockNumber,@VehicleVIN,
    @VehicleExteriorColor,@VehicleInteriorColor,@VehicleMileage,@VehicleType,
    @InServiceDate,@LeaseAnnualMiles,@ExtendedWarrantyName,@ExtendedWarrantyTerm,
    @ExtendedWarrantyLimitMiles,@LicensePlateNumber,@ModelDescriptionOfCarSold,
    @VehicleClassification,@ModelNumberOfCarSold,@ExtendedWarrantyFlag,
    @TrimLevel,@SubTrimLevel,@BodyDescription,@BodyDoorCount,
    @TransmissionDesc,@EngineDesc,@TypeCode,@Weight,@LeaseEstimatedMiles
    --======================================================================================
    --Insert into SALES_FEE Table
    INSERT INTO SALES_FEE
    SalesID ,
    Fee_Name ,
    Fee_Fee ,
    Fee_Commission
    VALUES (
    @SalesID,
    case
    when @Fee_1_Name is not null then @Fee_1_Name
    when @Fee_2_Name is not null then @Fee_2_Name
    when @Fee_3_Name is not null then @Fee_3_Name
    when @Fee_4_Name is not null then @Fee_4_Name
    when @Fee_5_Name is not null then @Fee_5_Name
    when @Fee_6_Name is not null then @Fee_6_Name
    when @Fee_7_Name is not null then @Fee_7_Name
    when @Fee_8_Name is not null then @Fee_8_Name
    when @Fee_9_Name is not null then @Fee_9_Name
    else @Fee_10_Name end,
    case
    when @Fee_1_Fee is not null then @Fee_1_Fee
    when @Fee_2_Fee is not null then @Fee_2_Fee
    when @Fee_3_Fee is not null then @Fee_3_Fee
    when @Fee_4_Fee is not null then @Fee_4_Fee
    when @Fee_5_Fee is not null then @Fee_5_Fee
    when @Fee_6_Fee is not null then @Fee_6_Fee
    when @Fee_7_Fee is not null then @Fee_7_Fee
    when @Fee_8_Fee is not null then @Fee_8_Fee
    when @Fee_9_Fee is not null then @Fee_9_Fee
    else @Fee_10_Fee end,
    case
    when @Fee_1_Commission is not null then @Fee_1_Commission
    when @Fee_2_Commission is not null then @Fee_2_Commission
    when @Fee_3_Commission is not null then @Fee_3_Commission
    when @Fee_4_Commission is not null then @Fee_4_Commission
    when @Fee_5_Commission is not null then @Fee_5_Commission
    when @Fee_6_Commission is not null then @Fee_6_Commission
    when @Fee_7_Commission is not null then @Fee_7_Commission
    when @Fee_8_Commission is not null then @Fee_8_Commission
    when @Fee_9_Commission is not null then @Fee_9_Commission
    else @Fee_10_Commission end
    --======================================================================================
    --Insert into SALES_HR Table
    INSERT INTO SALES_HR
    SalesID ,
    Salesman_Number ,
    Salesman_Name ,
    ClosingManagerName ,
    ClosingManagerNumber ,
    F_AND_I_ManagerNumber ,
    F_AND_I_ManagerName ,
    SalesManagerNumber ,
    SalesManagerName
    VALUES (
    @SalesID ,
    case
    when @Salesman_1_Number is not null then @Salesman_1_Number
    when @Salesman_2_Number is not null then @Salesman_2_Number
    when @Salesman_3_Number is not null then @Salesman_3_Number
    when @Salesman_4_Number is not null then @Salesman_4_Number
    when @Salesman_5_Number is not null then @Salesman_5_Number
    else @Salesman_6_Number end,
    case
    when @Salesman_1_Name is not null then @Salesman_1_Name
    when @Salesman_2_Name is not null then @Salesman_2_Name
    when @Salesman_3_Name is not null then @Salesman_3_Name
    when @Salesman_4_Name is not null then @Salesman_4_Name
    when @Salesman_5_Name is not null then @Salesman_5_Name
    else @Salesman_6_Name end,
    @ClosingManagerName ,
    @ClosingManagerNumber ,
    @F_AND_I_ManagerNumber ,
    @F_AND_I_ManagerName ,
    @SalesManagerNumber ,
    @SalesManagerName
    --======================================================================================
    --Insert into SALES_COBUYER Table
    INSERT INTO SALES_COBUYER
    SalesID ,
    CoBuyerName ,
    CoBuyerFirstName ,
    CoBuyerLastName ,
    CoBuyerAddress ,
    CoBuyerCity ,
    CoBuyerState ,
    CoBuyerZip ,
    CoBuyerCounty ,
    CoBuyerHomePhone ,
    CoBuyerWorkPhone ,
    CoBuyerBirthDate ,
    CoBuyerCustNum ,
    CoBuyerCell ,
    CoBuyerEmail ,
    CoBuyerSalutation ,
    CoBuyerMiddleName ,
    CoBuyerCountry ,
    CoBuyerAddress2 ,
    CoBuyerOptOut ,
    CoBuyerOccupation ,
    CoBuyerEmployer ,
    CoBuyerPhoneBlock ,
    CoBuyerMailBlock ,
    CoBuyerEmailBlock
    VALUES (
    @SalesID,@CoBuyerName,@CoBuyerFirstName,@CoBuyerLastName,@CoBuyerAddress,
    @CoBuyerCity,@CoBuyerState,@CoBuyerZip,@CoBuyerCounty,@CoBuyerHomePhone,
    @CoBuyerWorkPhone,@CoBuyerBirthDate,@CoBuyerCustNum,@CoBuyerCell,
    @CoBuyerEmail,@CoBuyerSalutation,@CoBuyerMiddleName,@CoBuyerCountry,
    @CoBuyerAddress2,@CoBuyerOptOut,@CoBuyerOccupation,@CoBuyerEmployer,
    @CoBuyerPhoneBlock,@CoBuyerMailBlock,@CoBuyerEmailBlock
    --======================================================================================
    --Insert into SALES_CUSTOMER Table
    INSERT INTO SALES_CUSTOMER
    SalesID ,
    IndividualBusinessFlag ,
    PhoneBlock ,
    EmailBlock ,
    CustomerName ,
    CustomerFirstName ,
    CustomerLastName ,
    CustomerAddress ,
    CustomerCity ,
    CustomerState ,
    CustomerZip ,
    CustomerCounty ,
    CustomerHomePhone ,
    CustomerWorkPhone ,
    CustomerCellPhone ,
    CustomerPagerPhone ,
    CustomerEmail ,
    CustomerBirthDate ,
    MailBlock ,
    CustomerSuffix ,
    CustomerSalutation ,
    CustomerAddress2 ,
    CustomerMiddleName ,
    GlobalOptOut ,
    InsuranceName ,
    InsuranceAgentName ,
    InsuranceAddress ,
    InsuranceCity ,
    InsuranceState ,
    InsuranceZip ,
    InsurancePhone ,
    InsurancePolicyNumber ,
    InsuranceEffectiveDate ,
    InsuranceExpirationDate ,
    InsuranceCompensationDeduction ,
    Country ,
    Occupation ,
    Employer ,
    CASS_STD_LINE1 ,
    CASS_STD_LINE2 ,
    CASS_STD_CITY ,
    CASS_STD_STATE ,
    CASS_STD_ZIP ,
    CASS_STD_ZIP4 ,
    CASS_STD_DPBC ,
    CASS_STD_CHKDGT ,
    CASS_STD_CART ,
    CASS_STD_LOT ,
    CASS_STD_LOTORD ,
    CASS_STD_URB ,
    CASS_STD_FIPS ,
    CASS_STD_EWS ,
    CASS_STD_LACS ,
    CASS_STD_ZIPMOV ,
    CASS_STD_Z4LOM ,
    CASS_STD_NDIAPT ,
    CASS_STD_NDIRR ,
    CASS_STD_LACSRT ,
    CASS_STD_ERROR_CD ,
    NCOA_AC_ID ,
    NCOA_COA_ADDSRC ,
    NCOA_COA_MATCH ,
    NCOA_COA_MOVTYP ,
    NCOA_COA_DATE ,
    NCOA_COA_DELCD ,
    NCOA_COA_RTYPE ,
    NCOA_COA_RTNCD ,
    NCOA_COA_LINE1 ,
    NCOA_COA_LINE2 ,
    NCOA_COA_CITY ,
    NCOA_COA_STATE ,
    NCOA_COA_ZIP ,
    NCOA_COA_ZIP4 ,
    NCOA_COA_DPBC ,
    NCOA_COA_CHKDGT ,
    NCOA_COA_CART ,
    NCOA_COA_LOT ,
    NCOA_COA_LOTORD ,
    NCOA_COA_URB ,
    NCOA_COA_Z4LOM ,
    NCOA_COA_ACTION ,
    NCOA_COA_QNAME ,
    NCOA_DPV_AA ,
    NCOA_DPV_A1 ,
    NCOA_DPV_BB ,
    NCOA_DPV_CC ,
    NCOA_DPV_M1 ,
    NCOA_DPV_M3 ,
    NCOA_DPV_N1 ,
    NCOA_DPV_P1 ,
    NCOA_DPV_P3 ,
    NCOA_DPV_RR ,
    NCOA_DPV_R1 ,
    NCOA_DPV_STATUS ,
    NCOA_DPV_F1 ,
    NCOA_DPV_G1 ,
    NCOA_DPV_U1
    VALUES (
    @SalesID ,
    @IndividualBusinessFlag ,
    @PhoneBlock ,
    @EmailBlock ,
    @CustomerName ,
    @CustomerFirstName ,
    @CustomerLastName ,
    @CustomerAddress ,
    @CustomerCity ,
    @CustomerState ,
    @CustomerZip ,
    @CustomerCounty ,
    @CustomerHomePhone ,
    @CustomerWorkPhone ,
    @CustomerCellPhone ,
    @CustomerPagerPhone ,
    @CustomerEmail ,
    @CustomerBirthDate ,
    @MailBlock ,
    @CustomerSuffix ,
    @CustomerSalutation ,
    @CustomerAddress2 ,
    @CustomerMiddleName ,
    @GlobalOptOut ,
    @InsuranceName ,
    @InsuranceAgentName ,
    @InsuranceAddress ,
    @InsuranceCity ,
    @InsuranceState ,
    @InsuranceZip ,
    @InsurancePhone ,
    @InsurancePolicyNumber ,
    @InsuranceEffectiveDate ,
    @InsuranceExpirationDate ,
    @InsuranceCompensationDeduction ,
    @Country ,
    @Occupation ,
    @Employer ,
    @CASS_STD_LINE1 ,
    @CASS_STD_LINE2 ,
    @CASS_STD_CITY ,
    @CASS_STD_STATE ,
    @CASS_STD_ZIP ,
    @CASS_STD_ZIP4 ,
    @CASS_STD_DPBC ,
    @CASS_STD_CHKDGT ,
    @CASS_STD_CART ,
    @CASS_STD_LOT ,
    @CASS_STD_LOTORD ,
    @CASS_STD_URB ,
    @CASS_STD_FIPS ,
    @CASS_STD_EWS ,
    @CASS_STD_LACS ,
    @CASS_STD_ZIPMOV ,
    @CASS_STD_Z4LOM ,
    @CASS_STD_NDIAPT ,
    @CASS_STD_NDIRR ,
    @CASS_STD_LACSRT ,
    @CASS_STD_ERROR_CD ,
    @NCOA_AC_ID ,
    @NCOA_COA_ADDSRC ,
    @NCOA_COA_MATCH ,
    @NCOA_COA_MOVTYP ,
    @NCOA_COA_DATE ,
    @NCOA_COA_DELCD ,
    @NCOA_COA_RTYPE ,
    @NCOA_COA_RTNCD ,
    @NCOA_COA_LINE1 ,
    @NCOA_COA_LINE2 ,
    @NCOA_COA_CITY ,
    @NCOA_COA_STATE ,
    @NCOA_COA_ZIP ,
    @NCOA_COA_ZIP4 ,
    @NCOA_COA_DPBC ,
    @NCOA_COA_CHKDGT ,
    @NCOA_COA_CART ,
    @NCOA_COA_LOT ,
    @NCOA_COA_LOTORD ,
    @NCOA_COA_URB ,
    @NCOA_COA_Z4LOM ,
    @NCOA_COA_ACTION ,
    @NCOA_COA_QNAME ,
    @NCOA_DPV_AA ,
    @NCOA_DPV_A1 ,
    @NCOA_DPV_BB ,
    @NCOA_DPV_CC ,
    @NCOA_DPV_M1 ,
    @NCOA_DPV_M3 ,
    @NCOA_DPV_N1 ,
    @NCOA_DPV_P1 ,
    @NCOA_DPV_P3 ,
    @NCOA_DPV_RR ,
    @NCOA_DPV_R1 ,
    @NCOA_DPV_STATUS ,
    @NCOA_DPV_F1 ,
    @NCOA_DPV_G1 ,
    @NCOA_DPV_U1
    --======================================================================================
    --Insert into SALES_AMOUNT Table
    INSERT INTO SALES_AMOUNT
    SalesID ,
    HoldBackAmount ,
    ExtendedWarrantyDollar ,
    ExtendedWarrantyProfit ,
    FrontGross ,
    BackGross ,
    MileageRate ,
    APRRate ,
    ResidualAmount ,
    LicenseFee ,
    RegistrationFee ,
    TotalTax ,
    Cost ,
    InvoiceAmount ,
    FinanceCharge ,
    TotalPickupPayment ,
    TotalAccessories ,
    TotalDriveOffAmount ,
    SalesmanCommission ,
    GrossProfitSale ,
    FinanceReserve ,
    CreditLifePremium ,
    CreditLifeCommision ,
    TotalInsuranceReserve ,
    BalloonAmount ,
    CashPrice ,
    AmountFinanced ,
    TotalOfPayments ,
    MSRP ,
    DownPayment ,
    SecurityDesposit ,
    Rebate ,
    Term ,
    RetailPayment ,
    LeasePayment ,
    LeaseNetCapCost ,
    LeaseTotalCapReduction ,
    APRRate2 ,
    APRRate3 ,
    GAPPremium ,
    LeaseTerm ,
    CashDeposit ,
    AHPremium ,
    LeaseRate ,
    Incentives ,
    StateDMVTotFee ,
    BuyRate ,
    DMVAmount ,
    CreditLifePrem ,
    CreditLifeRes ,
    AHRes ,
    Salesman2Commission ,
    ListPrice ,
    NetTradeAmount ,
    APRRate4 ,
    Term2 ,
    SecurityDeposit2 ,
    DownPayment2 ,
    TotalOfPayments2 ,
    BasePayment ,
    JournalSaleAmount
    VALUES (
    @SalesID,@HoldBackAmount,@ExtendedWarrantyDollar,@ExtendedWarrantyProfit,
    @FrontGross,@BackGross,@MileageRate,@APRRate,@ResidualAmount,@LicenseFee,
    @RegistrationFee,@TotalTax,@Cost,@InvoiceAmount,@FinanceCharge,
    @TotalPickupPayment,@TotalAccessories,@TotalDriveOffAmount,@SalesmanCommission,
    @GrossProfitSale,@FinanceReserve,@CreditLifePremium,@CreditLifeCommision,
    @TotalInsuranceReserve,@BalloonAmount,@CashPrice,@AmountFinanced,@TotalOfPayments,
    @MSRP,@DownPayment,@SecurityDesposit,@Rebate,@Term,@RetailPayment,@LeasePayment,
    @LeaseNetCapCost,@LeaseTotalCapReduction,@APRRate2,@APRRate3,@GAPPremium,
    @LeaseTerm,@CashDeposit,@AHPremium,@LeaseRate,@Incentives,@StateDMVTotFee,
    @BuyRate,@DMVAmount,@CreditLifePrem,@CreditLifeRes,@AHRes,@Salesman2Commission,
    @ListPrice,@NetTradeAmount,@APRRate4,@Term2,@SecurityDeposit2,
    @DownPayment2,@TotalOfPayments2,@BasePayment,@JournalSaleAmount
    --===========================================================================
    --Insert into SALES_BANKINFO Table
    INSERT INTO SALES_BANKINFO
    SalesID ,
    SLCT2 ,
    DealDateOffset ,
    DealerSelect ,
    DealStatus ,
    DealType ,
    SaleType ,
    BankCode ,
    BankName ,
    PaymentType ,
    BankAddress ,
    BankCity ,
    BankState ,
    BankZip ,
    AFTReserve ,
    Language ,
    ROSNumber
    VALUES (
    @SalesID,@SLCT2,@DealDateOffset,@DealerSelect,@DealStatus,@DealType,
    @SaleType,@BankCode,@BankName,@PaymentType,@BankAddress,@BankCity,
    @BankState,@BankZip,@AFTReserve,@Language,@ROSNumber
    ---=======================================================
    INSERT INTO SALES_DATE
    SalesID ,
    AccountingDate ,
    InventoryDate ,
    StatusDate ,
    LastInstallmentDate ,
    RetailFirstPayDate ,
    LeaseFirstPayDate ,
    DayToFirstPayment ,
    EntryDate ,
    DealBookDate ,
    RealBookDate
    VALUES (
    @SalesID ,
    convert (datetime,@AccountingDate) ,
    -- CAST (@AccountingDate AS datetime),
    convert (datetime,@InventoryDate) ,
    -- CAST (@InventoryDate AS datetime),
    convert (datetime,@StatusDate) ,
    -- CAST (@StatusDate AS datetime),
    convert (datetime,@LastInstallmentDate),
    -- CAST (@LastInstallmentDate AS datetime),
    convert (datetime,@RetailFirstPayDate) ,
    -- CAST (@RetailFirstPayDate AS datetime),
    @LeaseFirstPayDate ,
    convert (datetime,@DayToFirstPayment),
    -- CAST (@DayToFirstPayment AS datetime),
    convert (datetime,@EntryDate),
    -- CAST (@EntryDate AS datetime),
    convert (datetime,@DealBookDate),
    -- CAST (@DealBookDate AS datetime),
    convert (datetime,@RealBookDate)
    -- CAST (@RealBookDate AS datetime)
    */---=======================================================
    --======================================================================================
    -- Move cursor to Next record
    FETCH NEXT FROM Sales_Cursor
    INTO @FileType ,
    @ACDealerID ,
    @ClientDealerID ,
    @DMSType ,
    @DealNumber ,
    @CustomerNumber ,
    @CustomerName ,
    @CustomerFirstName ,
    @CustomerLastName ,
    @CustomerAddress ,
    @CustomerCity ,
    @CustomerState ,
    @CustomerZip ,
    @CustomerCounty ,
    @CustomerHomePhone ,
    @CustomerWorkPhone ,
    @CustomerCellPhone ,
    @CustomerPagerPhone ,
    @CustomerEmail ,
    @CustomerBirthDate ,
    @MailBlock ,
    @CoBuyerName ,
    @CoBuyerFirstName ,
    @CoBuyerLastName ,
    @CoBuyerAddress ,
    @CoBuyerCity ,
    @CoBuyerState ,
    @CoBuyerZip ,
    @CoBuyerCounty ,
    @CoBuyerHomePhone ,
    @CoBuyerWorkPhone ,
    @CoBuyerBirthDate ,
    @Salesman_1_Number ,
    @Salesman_1_Name ,
    @Salesman_2_Number ,
    @Salesman_2_Name ,
    @ClosingManagerName ,
    @ClosingManagerNumber ,
    @F_AND_I_ManagerNumber ,
    @F_AND_I_ManagerName ,
    @SalesManagerNumber ,
    @SalesManagerName ,
    @EntryDate ,
    @DealBookDate ,
    @VehicleYear ,
    @VehicleMake ,
    @VehicleModel ,
    @VehicleStockNumber ,
    @VehicleVIN ,
    @VehicleExteriorColor ,
    @VehicleInteriorColor ,
    @VehicleMileage ,
    @VehicleType ,
    @InServiceDate ,
    @HoldBackAmount ,
    @DealType ,
    @SaleType ,
    @BankCode ,
    @BankName ,
    @SalesmanCommission ,
    @GrossProfitSale ,
    @FinanceReserve ,
    @CreditLifePremium ,
    @CreditLifeCommision ,
    @TotalInsuranceReserve ,
    @BalloonAmount ,
    @CashPrice ,
    @AmountFinanced ,
    @TotalOfPayments ,
    @MSRP ,
    @DownPayment ,
    @SecurityDesposit ,
    @Rebate ,
    @Term ,
    @RetailPayment ,
    @PaymentType ,
    @RetailFirstPayDate ,
    @LeaseFirstPayDate ,
    @DayToFirstPayment ,
    @LeaseAnnualMiles ,
    @MileageRate ,
    @APRRate ,
    @ResidualAmount ,
    @LicenseFee ,
    @RegistrationFee ,
    @TotalTax ,
    @ExtendedWarrantyName ,
    @ExtendedWarrantyTerm ,
    @ExtendedWarrantyLimitMiles ,
    @ExtendedWarrantyDollar ,
    @ExtendedWarrantyProfit ,
    @FrontGross ,
    @BackGross ,
    @TradeIn_1_VIN ,
    @TradeIn_2_VIN ,
    @TradeIn_1_Make ,
    @TradeIn_2_Make ,
    @TradeIn_1_Model ,
    @TradeIn_2_Model ,
    @TradeIn_1_ExteriorColor ,
    @TradeIn_2_ExteriorColor ,
    @TradeIn_1_Year ,
    @TradeIn_2_Year ,
    @TradeIn_1_Mileage ,
    @TradeIn_2_Mileage ,
    @TradeIn_1_Gross ,
    @TradeIn_2_Gross ,
    @TradeIn_1_Payoff ,
    @TradeIn_2_Payoff ,
    @TradeIn_1_ACV ,
    @TradeIn_2_ACV ,
    @Fee_1_Name ,
    @Fee_1_Fee ,
    @Fee_1_Commission ,
    @Fee_2_Name ,
    @Fee_2_Fee ,
    @Fee_2_Commission ,
    @Fee_3_Name ,
    @Fee_3_Fee ,
    @Fee_3_Commission ,
    @Fee_4_Name ,
    @Fee_4_Fee ,
    @Fee_4_Commission ,
    @Fee_5_Name ,
    @Fee_5_Fee ,
    @Fee_5_Commission ,
    @Fee_6_Name ,
    @Fee_6_Fee ,
    @Fee_6_Commission ,
    @Fee_7_Name ,
    @Fee_7_Fee ,
    @Fee_7_Commission ,
    @Fee_8_Name ,
    @Fee_8_Fee ,
    @Fee_8_Commission ,
    @Fee_9_Name ,
    @Fee_9_Fee ,
    @Fee_9_Commission ,
    @Fee_10_Name ,
    @Fee_10_Fee ,
    @Fee_10_Commission ,
    @ContractDate ,
    @InsuranceName ,
    @InsuranceAgentName ,
    @InsuranceAddress ,
    @InsuranceCity ,
    @InsuranceState ,
    @InsuranceZip ,
    @InsurancePhone ,
    @InsurancePolicyNumber ,
    @InsuranceEffectiveDate ,
    @InsuranceExpirationDate ,
    @InsuranceCompensationDeduction ,
    @TradeIn_1_InteriorColor ,
    @TradeIn_2_InteriorColor ,
    @PhoneBlock ,
    @LicensePlateNumber ,
    @Cost ,
    @InvoiceAmount ,
    @FinanceCharge ,
    @TotalPickupPayment ,
    @TotalAccessories ,
    @TotalDriveOffAmount ,
    @EmailBlock ,
    @ModelDescriptionOfCarSold ,
    @VehicleClassification ,
    @ModelNumberOfCarSold ,
    @GAPPremium ,
    @LastInstallmentDate ,
    @CashDeposit ,
    @AHPremium ,
    @LeaseRate ,
    @DealerSelect ,
    @LeasePayment ,
    @LeaseNetCapCost ,
    @LeaseTotalCapReduction ,
    @DealStatus ,
    @CustomerSuffix ,
    @CustomerSalutation ,
    @CustomerAddress2 ,
    @CustomerMiddleName ,
    @GlobalOptOut ,
    @LeaseTerm ,
    @ExtendedWarrantyFlag ,
    @Salesman_3_Number ,
    @Salesman_3_Name ,
    @Salesman_4_Number ,
    @Salesman_4_Name ,
    @Salesman_5_Number ,
    @Salesman_5_Name ,
    @Salesman_6_Number ,
    @Salesman_6_Name ,
    @APRRate2 ,
    @APRRate3 ,
    @APRRate4 ,
    @Term2 ,
    @SecurityDeposit2 ,
    @DownPayment2 ,
    @TotalOfPayments2 ,
    @BasePayment ,
    @JournalSaleAmount ,
    @IndividualBusinessFlag ,
    @InventoryDate ,
    @StatusDate ,
    @ListPrice ,
    @NetTradeAmount ,
    @TrimLevel ,
    @SubTrimLevel ,
    @BodyDescription ,
    @BodyDoorCount ,
    @TransmissionDesc ,
    @EngineDesc ,
    @TypeCode ,
    @SLCT2 ,
    @DealDateOffset ,
    @AccountingDate ,
    @CoBuyerCustNum ,
    @CoBuyerCell ,
    @CoBuyerEmail ,
    @CoBuyerSalutation ,
    @CoBuyerPhoneBlock ,
    @CoBuyerMailBlock ,
    @CoBuyerEmailBlock ,
    @RealBookDate ,
    @CoBuyerMiddleName ,
    @CoBuyerCountry ,
    @CoBuyerAddress2 ,
    @CoBuyerOptOut ,
    @CoBuyerOccupation ,
    @CoBuyerEmployer ,
    @Country ,
    @Occupation ,
    @Employer ,
    @Salesman2Commission ,
    @BankAddress ,
    @BankCity ,
    @BankState ,
    @BankZip ,
    @LeaseEstimatedMiles ,
    @AFTReserve ,
    @CreditLifePrem ,
    @CreditLifeRes ,
    @AHRes ,
    @Language ,
    @BuyRate ,
    @DMVAmount ,
    @Weight ,
    @StateDMVTotFee ,
    @ROSNumber ,
    @Incentives ,
    @CASS_STD_LINE1 ,
    @CASS_STD_LINE2 ,
    @CASS_STD_CITY ,
    @CASS_STD_STATE ,
    @CASS_STD_ZIP ,
    @CASS_STD_ZIP4 ,
    @CASS_STD_DPBC ,
    @CASS_STD_CHKDGT ,
    @CASS_STD_CART ,
    @CASS_STD_LOT ,
    @CASS_STD_LOTORD ,
    @CASS_STD_URB ,
    @CASS_STD_FIPS ,
    @CASS_STD_EWS ,
    @CASS_STD_LACS ,
    @CASS_STD_ZIPMOV ,
    @CASS_STD_Z4LOM ,
    @CASS_STD_NDIAPT ,
    @CASS_STD_NDIRR ,
    @CASS_STD_LACSRT ,
    @CASS_STD_ERROR_CD ,
    @NCOA_AC_ID ,
    @NCOA_COA_ADDSRC ,
    @NCOA_COA_MATCH ,
    @NCOA_COA_MOVTYP ,
    @NCOA_COA_DATE ,
    @NCOA_COA_DELCD ,
    @NCOA_COA_RTYPE ,
    @NCOA_COA_RTNCD ,
    @NCOA_COA_LINE1 ,
    @NCOA_COA_LINE2 ,
    @NCOA_COA_CITY ,
    @NCOA_COA_STATE ,
    @NCOA_COA_ZIP ,
    @NCOA_COA_ZIP4 ,
    @NCOA_COA_DPBC ,
    @NCOA_COA_CHKDGT ,
    @NCOA_COA_CART ,
    @NCOA_COA_LOT ,
    @NCOA_COA_LOTORD ,
    @NCOA_COA_URB ,
    @NCOA_COA_Z4LOM ,
    @NCOA_COA_ACTION ,
    @NCOA_COA_QNAME ,
    @NCOA_DPV_AA ,
    @NCOA_DPV_A1 ,
    @NCOA_DPV_BB ,
    @NCOA_DPV_CC ,
    @NCOA_DPV_M1 ,
    @NCOA_DPV_M3 ,
    @NCOA_DPV_N1 ,
    @NCOA_DPV_P1 ,
    @NCOA_DPV_P3 ,
    @NCOA_DPV_RR ,
    @NCOA_DPV_R1 ,
    @NCOA_DPV_STATUS ,
    @NCOA_DPV_F1 ,
    @NCOA_DPV_G1 ,
    @NCOA_DPV_U1;
    END
    CLOSE Sales_Cursor;
    DEALLOCATE Sales_Cursor;
    GO
    SET ANSI_PADDING OFF
    GO

    Duplicate thread:
    problem - original

  • How to insert CLOB value through a procedure

    Hi,
    There is one clob field in a table. I have created the
    following procedure to insert values into the table.
    create or replace procedure temp_proc (col1 in number,
                   col2 in varchar2,
                        col3 in clob) is
    sql_stmt varchar2(500);
    begin
    sql_stmt := 'insert into temp_table values
    (:col1, :col2, :col3)';
    execute immediate sql_stmt using col1, col2, col3;
    end temp_proc;
    I could able to insert values into the table through INSERT
    statement from sql*plus. When I am executing the above procedure
    from sql*plus, getting the follwing error.
    BEGIN temp_proc(1,'fdsfds','hghgh'); END;
    ERROR at line 1:
    ORA-06550: line 1, column 7:
    PLS-00306: wrong number or types of arguments in call
    to 'TEMP_PROC'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    If I change the datatype of third parameter in the above
    procedure to varchar2, it's working fine. But it should be a
    clob field because getting huge data from other application.
    Please let me know how to overcome this problem.
    Thank you.

    hi,
    In the CLOB column you can insert the data as inline if it's
    length is lessthan < 4000 bytes. if it it exceedes this will be
    stored as
    So change the column 3 as varchar2 in your procedure , then it
    will work. No need to change in your table.
    create or replace procedure temp_proc
    col1 in number,
    col2 in varchar2,
    col3 in varchar2
    ) is
    sql_stmt varchar2(500);
    begin
    sql_stmt := 'insert into temp_table values
    (:col1, :col2, :col3)';
    execute immediate sql_stmt using col1, col2, col3;
    end temp_proc;
    regards,
    khaleel

  • Bulk Insert Through Stored Procedure performance issue

    Hello,
    i am new to oracle. i am writing a stored procedure through which i want to insert 1 billion record in a table. but it takes days to insert it . please tell me how can i improve performance of my stored procedure. because same stored procedure when i convert it into sql server in take 24 - 30 min to insert 1 billion record.
    Code of my stored procedure are as follows :
    create or replace PROCEDURE bspGenerateHSCode(
    mLoc_id IN INT,
    HSCodeStart IN VARCHAR2,
    HSCodeEnd IN VARCHAR2,
    mRqstId IN INT,
    total_count IN INT,
    Status OUT INT)
    AS
    ExitFlag INT;
    row_count INT;
    mBatchStart NUMBER;
    mBatchEnd NUMBER;
    mStartSqnc NUMBER;
    mEndSqnc NUMBER;
    mHSCode VARCHAR2(500);
    HSStartStr VARCHAR2(500);
    BEGIN
    SELECT COUNT(*) INTO row_count FROM goap_eal_allocation
                   WHERE hs_code_start = HSCodeStart
    AND hs_code_end = HSCodeEnd
    AND loc_id = mLoc_id
    AND processed = 0;
    IF row_count > 0 THEN
    SELECT CAST ( REVERSE(substr(REVERSE(HSCodeStart), 1, instr(REVERSE(HSCodeStart), ',') -1)) AS NUMBER) INTO mStartSqnc FROM DUAL;
    SELECT CAST ( REVERSE(substr(REVERSE(HSCodeEnd), 1, instr(REVERSE(HSCodeEnd), ',') -1)) AS NUMBER) INTO mEndSqnc FROM DUAL;
    SELECT CAST( REVERSE(substr( REVERSE(HSCodeStart), instr(REVERSE(HSCodeStart), ','))) AS VARCHAR2(500) ) INTO HSStartStr FROM DUAL;
    mBatchStart := mStartSqnc;
    DBMS_OUTPUT.PUT_LINE('start batch ' || mBatchStart);
    LOOP
    mBatchEnd := mBatchStart + 5000;
    IF mBatchEnd > mEndSqnc THEN
    mBatchEnd := mEndSqnc + 1;
    END IF;
    DBMS_OUTPUT.PUT_LINE('End batch ' || mBatchEnd);
    LOOP
    mHSCode := HSStartStr || mBatchStart;
    mBatchStart := mBatchStart + 1;
    INSERT INTO goap_eal_register(id, hs_code, loc_id, status_id, synced)
    SELECT CASE WHEN MAX(id) > 0 THEN (MAX(id) + 1) ELSE 1 END AS id ,
    mHSCode, mLoc_id, 6, 1 FROM goap_eal_register;
    EXIT WHEN mBatchStart = mBatchEnd;
    END LOOP;
    COMMIT;
    EXIT WHEN mBatchStart = mEndSqnc +1;
    END LOOP;
    UPDATE goap_eal_allocation SET processed = 1
    WHERE hs_code_start = HSCodeStart
    AND hs_code_end = HSCodeEnd
    AND loc_id = mLoc_id;
    COMMIT;
    Status := 1;
    ELSE
    Status := 0;
    END IF;
    END;
    Thanks

    Please edit your post and add \ on the line before and the line after the code to preserve formattingsee how this looks?
    Also, when you basically just want to RETURN without doing any work then your first test should just RETURN if you don't want to do any work.
    Instead of what your code does:IF row_count > 0 THEN
    . . . a whole lot of code that is hard to read or understand
    COMMIT;
    Status := 1;
    ELSE
    Status := 0;
    END IF;
    Test the condition to determine when you do NOT want proceed and just return.IF row_count = 0 THEN
    Status := 0;
    RETURN;
    END IF;
    -- now NONE of the following code needs to be indented - you won't get here unless you really want to execute it.
    . . . break the code into separate steps and add a one line comment before each step that says what that step does.
    COMMIT;
    Status := 1;

  • Stored procedure to insert into multiple tables in sql server 2012, using id col from one table to insert into the other 2

    Hi all,
    Apologies if any of the following sounds at all silly but I am fairly new to this so here goes...
    I have 3 tables that require data insertion at the same time. The first table is the customers table, I then want to take the automatically generated custid from that table and inser it into 2 other tables along with some other data
    Here's what I have so far which does not work:
    CREATE PROCEDURE CustomerDetails.bnc_insNewRegistration @CustId int,
    @CompanyName varchar(100),
    @FirstName varchar(50),
    @LastName varchar(50),
    @Email nvarchar(254),
    @HouseStreet varchar(100),
    @Town smallint,
    @County tinyint,
    @Postcode char(8),
    @Password nvarchar(20)
    AS
    BEGIN
    begin tran
    insert into CustomerDetails.Customers
    (CompanyName, FirstName, LastName, EmailAddress)
    Values (@CompanyName, @FirstName, @LastName, @Email)
    set @CustId = (select CustId from inserted)
    insert into CustomerDetails.Address
    (CustomerId, HouseNoAndStreet, Town, County, PostCode)
    values (@CustId, @HouseStreet, @Town, @County, @Postcode)
    insert into CustomerDetails.MembershipDetails
    (CustomerId, UserName, Password)
    values (@CustId, @Email, @Password)
    commit tran
    END
    GO
    If anyone could help with this I would very much appreciate it as I am currently building an online store, if there's no registration there's no customers.
    So to whom ever is able to help, I thank you whole heartedly :)

    I hope by now it is apparent that statements like "doesn't work" are not particularly helpful. The prior posts have already identified your first problem.  But there are others.  First, you have declared @CustID as an argument for your
    procedure - but it is obvious that you do not expect a useful value to be supplied when the procedure is executed.  Perhaps it should be declared as an output argument so that the caller of the procedure can know the PK value of the newly inserted customer
    - otherwise, replace it with a local variable since it serves no purpose as an input argument.
    Next, you are storing email twice.  Duplication of data contradicts relational theory and will only cause future problems. 
    Next, I get the sense that your "customer" can be a person or a company.  You may find that using the same table for both is not the best approach.  I hope you have constraints to prevent a company from having a first and last name (and
    vice versa).
    Next, your error checking is inadequate.  We can only hope that you have the appropriate constraints to prevent duplicates.  You should expect failures to occur, from basic data errors (duplicates, null values, inconsistent values) to system issues
    (out of space).  I'll leave you with Erland's discussion for more detail:
    erland - error handling.
    Lastly, you should reconsider the datatypes you are using for the various bits of information.  Presumably town and county are foreign keys to related tables, which is why they are numeric.  Be careful you don't paint yourself into a corner with
    such small datatypes.  One can also debate the wisdom of using a separate tables for Town and County (and perhaps the decision to limit yourself to a particular geographic area with a particular civic hierarchy). Password seems a little short to me. 
    And if you are going to use nvarchar for some strings, you might as well use it for everything - especially names.  Also, everyone should be security conscious by now - passwords should be encrypted at the very least.
    And one last comment - you really should allow 2 address lines. Yes, two separate ones and not just one much larger one.

  • How do i insert into table through forms

    Hi
    I have developed a custom form based on custom table.
    the only way to insert data into database table is through form.
    there are two tables: one table is to store all contract details & second table is to maintain history forthis.
    one condition(col1,col2,col3,col4) are unique combination,we are not creating any PK or FK at database level.evrythng is captured at form level.
    if all 4 columns combination exist thn e should not insert that record.
    if 4 columns combination doesnot exist then insert into table.
    I have used just pre insert,pre update triggers.
    I think its a basic form functionality ,by itself it inserts ,update record.now it is doing the same thng.
    But I have to add the above condition ,how can i do that.
    Pl provide me some ex code .
    Thank you.
    Hope any one can help me

    SQL> create table t
      2  (object_id    number
      3  ,object_name  varchar2(30));
    Table created.
    SQL>
    SQL> create sequence t_seq;
    Sequence created.
    SQL>
    SQL> insert into t (object_id, object_name)
      2  select t_seq.nextval
      3        ,object_name
      4  from   all_objects
      5  ;
    52637 rows created.

  • Problem in Insertion into table through After Report Parameter form trigger

    Hi All,
    I am getting problem in inserting some data into temp table through Report.
    My requirement is like that, I have to do a calculation based on user parameters, and then insert the data into the temp table. I wanted to do this into After Report Parameter form trigger function. I have done all the calculation and wrote all the insert statement in that function. There is no problem in compilation. then I am taking value from this temp table in my formula columns.
    When I run this report, it hangs, don't understand what is the problem.Can anybody help me out in this.
    Thanks,
    Nidhi

    The code is as follows:
    function AfterPForm return boolean is
    CURSOR CUR_RECEIPT(RECEIPT_NUM_FROM NUMBER, RECEIPT_NUM_TO NUMBER) IS
    SELECT DISTINCT receipt, item_no FROM xxeeg.xxeeg_1229_sp_putaway WHERE RECEIPT BETWEEN
    RECEIPT_NUM_FROM AND RECEIPT_NUM_TO ;
    V_CUR_RECEIPT CUR_RECEIPT%ROWTYPE;
    begin
    OPEN CUR_RECEIPT(:RECEIPT_NUM_FROM, :RECEIPT_NUM_TO);
    FETCH CUR_RECEIPT
    INTO V_CUR_RECEIPT;
    LOOP
    EXIT WHEN CUR_RECEIPT%NOTFOUND;
    IF V_CUR_RECEIPT.ITEM_NO = 'TEST1' AND V_CUR_RECEIPT.RECEIPT = '12' THEN
    INSERT INTO SP_TEMP
    (RECEIPT, ITEM_NO, LOCATION1)
    VALUES
    (V_CUR_RECEIPT.RECEIPT, V_CUR_RECEIPT.ITEM_NO, 10);
    UPDATE SP_TEMP
    SET LOCATION2 = 12
    WHERE RECEIPT = V_CUR_RECEIPT.RECEIPT AND ITEM_NO = V_CUR_RECEIPT.ITEM_NO;
    UPDATE SP_TEMP
    SET LOCATION3 = 13
    WHERE RECEIPT = V_CUR_RECEIPT.RECEIPT AND ITEM_NO = V_CUR_RECEIPT.ITEM_NO;
    UPDATE SP_TEMP
    SET LOCATION4 = 14
    WHERE RECEIPT = V_CUR_RECEIPT.RECEIPT AND ITEM_NO = V_CUR_RECEIPT.ITEM_NO;
    ELSE
    IF V_CUR_RECEIPT.ITEM_NO = 'TEST2' AND V_CUR_RECEIPT.RECEIPT = '12' THEN
    INSERT INTO SP_TEMP
    (RECEIPT, ITEM_NO, LOCATION1)
    VALUES
    (V_CUR_RECEIPT.RECEIPT, V_CUR_RECEIPT.ITEM_NO, 10);
    UPDATE SP_TEMP
    SET LOCATION2 = 16
    WHERE RECEIPT = V_CUR_RECEIPT.RECEIPT AND ITEM_NO = V_CUR_RECEIPT.ITEM_NO;
    UPDATE SP_TEMP
    SET LOCATION3 = 17
    WHERE RECEIPT = V_CUR_RECEIPT.RECEIPT AND ITEM_NO =V_CUR_RECEIPT.ITEM_NO;
    UPDATE SP_TEMP
    SET LOCATION4 = 18
    WHERE RECEIPT = V_CUR_RECEIPT.RECEIPT AND ITEM_NO = V_CUR_RECEIPT.ITEM_NO;
    ELSE
    INSERT INTO SP_TEMP
    (RECEIPT, ITEM_NO, LOCATION1)
    VALUES
    (V_CUR_RECEIPT.RECEIPT, V_CUR_RECEIPT.ITEM_NO, 10);
    UPDATE SP_TEMP
    SET LOCATION2 = 19
    WHERE RECEIPT = V_CUR_RECEIPT.RECEIPT AND ITEM_NO = V_CUR_RECEIPT.ITEM_NO;
    UPDATE SP_TEMP
    SET LOCATION3 = 20
    WHERE RECEIPT = V_CUR_RECEIPT.RECEIPT AND ITEM_NO =V_CUR_RECEIPT.ITEM_NO;
    UPDATE SP_TEMP
    SET LOCATION4 = 21
    WHERE RECEIPT = V_CUR_RECEIPT.RECEIPT AND ITEM_NO = V_CUR_RECEIPT.ITEM_NO;
    END IF;
    END IF;
    END LOOP;
    COMMIT;
    CLOSE CUR_RECEIPT;
    return(TRUE);
    end;
    .....................................................................................................................

  • Insert into a clob field in a procedure based form

    Hi,
    I have a table with a clob field. I wrote a procedure to insert into this table. Then I built a form based on this procedure. Here is my code:
    drop table clob_test;
    create table clob_test(id NUMBER, note CLOB);
    insert into clob_test values(10,empty_clob());
    Create or Replace PROCEDURE PROJECTS.SET_CLOB
    ( p_id IN CLOB_TEST.id%TYPE,
    p_note IN VARCHAR2 default null)
    as
    v_loc CLOB;
    v_amt binary_integer;
    v_pos integer :=1;
    v_clob varchar2(32000);
    Begin
    insert into clob_test values(p_id,empty_clob());
    v_clob := p_note;
    v_amt := LENGTH(v_clob);
    select note into v_loc from clob_test where id = p_id;
    DBMS_LOB.WRITE(v_loc,v_amt,v_pos,v_clob);
    End;
    When I try to insert into note field more than 4000 charaters. I got this error:
    An unexpected error occurred: ORA-06502: PL/SQL: numeric or value error: character string buffer too small (WWV-16016)
    Why this happens? I know portal form doesn't support clob, but this procedure deal directly with database. Can anyone from Oracle give me help? Thanks in advance!

    I use a dynamic page instead of a form on the procedure. It's working.
    Apparently Oracle is not supporting a varchar2 more than 4000 in any form format, even using textarea for p_note.

  • How to insert one table data into multiple tables by using procedure?

    How to insert one table data into multiple tables by using procedure?

    Below is the simple procedure. Try the below
    CREATE OR REPLACE PROCEDURE test_proc
    AS
    BEGIN
    INSERT ALL
      INTO emp_test1
      INTO emp_test2
      SELECT * FROM emp;
    END;
    If you want more examples you can refer below link
    multi-table inserts in oracle 9i
    Message was edited by: 000000

Maybe you are looking for

  • Open dialog box....

    Hi Everyone, I have designed a form in which user has to input the path where he wants to save his report. Like c:\test.PDF what i want to do is that when user click a button againts this field a dialog box should appear in which he can select the lo

  • Phone won't turn on

    My phone was working this morning and then it just shut off. I've tried resetting it and plugging it into itunes but itunes won't even recognize that the iphone is connected. Any ideas??

  • Don't wanna album artworks keep floating on the main menu

    Is there any way to disable album artworks keep floating on the main menu of iPod classic? I think Apple should give us a choice to disable this function with next iPod firmware update. Some album artworks I don't want to show up there. And the key p

  • Tab Control - change page name and color

    a) Is there any possibility to change the names of pages in a Tab Control programmatically? (I want to change the names in a runtime version depending on the user selected language. Therefore I can't use the Import Strings function.) b) Is it possibl

  • Macbook Pro Retina 15" External Display

    I have a Macbook Pro Retina 15" that I want to connect to a projector via HDMI connection. How do I turn on the External Display to present a Keynote Presentation? I have not tried it yet, will the Mackbook automatically connect to the projector when