Case in insert  statement

I am trying to use an case staemnet in oracle
create table test1 (Status varchar2(10);
declare
Status varchar2(02);
begin
Status := '1'
insert into test1 values (case Status when '1' then 'CREATE' when '2' then 'UPDATE' when '3' then 'DELETE else 'INVALID' end case);
end;
/

I'm assuming you're getting a bunch of syntax errors:
SQL> create table test1 (Status varchar2(10));
Table created.
SQL>
SQL> declare
  2  Status varchar2(02);
  3  begin
  4  Status := '1';
  5  insert into test1 values (case Status
  6                                 when '1' then 'CREATE'
  7                                 when '2' then 'UPDATE'
  8                                 when '3' then 'DELETE'
  9                                 else 'INVALID'
10                            end);
11  end;
12  /
PL/SQL procedure successfully completed.
SQL> select * from test1;
STATUS
CREATE

Similar Messages

  • Inserting multiple rows with single insert statement ?

    Hi ,,
    Consider a PL/SQL procedure.
    I want to pass an array of values and insert in a table with a single statement.
    Moreover I want to call this procedure to insert multiple rows from OCI program.
    Can some body help ? :(
    Thanks
    Chandu

    Hi Vincent,
    Regular array insert which you have mentioned works in case of insert statement(This is to eliminate multiple calls to server)
    Will it work for passing array to Stored procedure, in this case procedure will be called only once with an array.
    It will be of great help if you give an example.
    Thanks
    Chandra

  • Use of case  in an insert statement...

    Hi ,
    i have an insert statement in a db packaged procedure which needs a case statement to be used.....
    I want to use the case in a statement like the following...
    insert into x(a,b,c,d,e)
    values(a,b,case b='1' then c_val , d_val , null else null , null , e_val);
    In other words when the b_value (b column) has value '1' (in the example above) then the values for c , d columns of the tables are those passed as parameters to the procedure . On the other hand , when the the b_value (b column) has not value '1' then the values for c , d columns of the tables should be null and the on the e column another value passed as parameter to the procedure....????
    Is the above general syntax of insert correct...????
    Many thanks,
    Simon

    Something like this could do the trick:
    insert into x
                (a, b, c, d, e)
         values (a,
                 b,
                 case
                    when b = '1'
                       then c_val
                 end,
                 case
                    when b = '1'
                       then d_val
                 end,
                 case
                    when b = '1'
                       then null
                    else e_val
                 end
                );

  • Help needed in writing SQL CASE or DECODE statement

    Hi experts,
    I need to write a SQL to select order_num, cntry_cde, prod_id and Qty by joining order_num on PROD_ORDER and PROD_ORDER_TXT.
    Here is my sample data
    PRODORDER_               
    order_num     cntry_cde     Prod_id     Qty
    100     US     A1     5
    101     US     A2     10
    102     AU     A3     4
    103     AU     A4     9
    104     IN     A5     3
    PRODORDER_TXT_               
    order_num     cntry_cde     Prod_id     
    100     US     A1     
    101     US     A2     
    102     NZ     A3     
    103     AU     A4     
    104          A5     
    Here is the requirement,
    1) If the cntry_cde in PROD_ORDER is same as cntry_cde in PROD_ORDER_TXT then select PROD_ORDER.cntry_cde (orders 100, 101, 103)
    2) If they are different, pick the country code from PROD_ORDER_TXT (order 102, AU <> NZ)
    3) If they are different and PROD_ORDER_TXT.cntry_cde is NULL, I cannot use it as cntry_cde in my report (order 104). It happenend just because of the bad data at source.
    I cannot avoid it. Then simply use the cntry_cde from PROD_ORDER
    Output expected
    100     US     A1     5
    101     US     A2     10
    102     NZ     A3     4 -- AU changed to NZ
    103     AU     A4     9
    104     IN     A5     3 -- IN retained as PROD_ORDER_TXT.cntry_cde is null
    sample table creation and insert statements are below
    create table prod_order
    (order_num number,
    cntry_cde CHAR(2),
    prod_id VARCHAR2(6),
    qty number)
    create table prod_order_txt
    (order_num number,
    cntry_cde CHAR(2),
    prod_id VARCHAR2(6))
    insert into prod_order values (100, 'US', 'A1',5);
    insert into prod_order values (101, 'US', 'A2',1);
    insert into prod_order values (102, 'AU', 'A3',4);
    insert into prod_order values (103, 'AU', 'A4',9);
    insert into prod_order values (104, 'IN', 'A5',3);
    insert into prod_order_txt values (100,'US','A1');
    insert into prod_order_txt values (101,'US','A2');
    insert into prod_order_txt values (102,'NZ','A3');
    insert into prod_order_txt values (103,'AU','A4');
    insert into prod_order_txt values (104,NULL,'A5');
    commit;
    Thanks for your help in advance
    Edited by: sarvan on Mar 28, 2012 1:39 PM

    Hello
    Thank you for posting all of the ddl and test data along with your expected output - very helpful!. One small point would be to remember to type {noformat}{noformat} before and after any section of code or data in your post so that formatting is retained.  Anyway, this should be a simple join and a combination of CASE and NVL...Select
    po.order_num,
    CASE
    WHEN po.cntry_cde != NVL(pot.cntry_cde,po.cntry_cde)
    THEN
    pot.cntry_cde
    ELSE
    po.cntry_cde
    END cntry_code,
    po.prod_id,
    po.qty
    FROM
    prod_order po
    JOIN
    prod_order_txt pot
    ON
    ( po.order_num = pot.order_num
    ORDER_NUM CN PROD_I QTY
    100 US A1 5
    101 US A2 1
    102 NZ A3 4
    103 AU A4 9
    104 IN A5 3
    5 rows selected.
    HTH
    David
    Edited by: Bravid on Mar 28, 2012 8:32 AM
    corrected !=                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Issu for running insert statement in oracle procedure.

    Hi expert,
    I ran a oracle procedure with a insert statement inside as:
    insert into table1 select....
    but I got error message related to this insert statement as "SQLERRM= ORA-08103: object no longer exists"
    I ran this statement separately in toad, no error message, but no data result from this execute.
    please tell how to fix this issue.
    Many Thanks,
    Edited by: 918440 on 27-Jun-2012 8:04 AM

    Hi friend,
    my insert statement is as follows:
            INSERT INTO HIROC_RU_FACT_S   
            select   
                    pp.policy_fk,  
                    pp.transaction_log_fk,  
                    p.policy_no,  
                    p.policy_type_code,   
                    hiroc_rpt_user.hiroc_get_entity_name(pp.policy_fk,'POLHOLDER')  policy_holder,  
                    pp.risk_fk,   
                    r.risk_base_record_fk,   
                    r.entity_fk,  
                    hiroc_sel_entity_risk_name2 (pp.risk_fk,r.entity_fk)  risk_name,   
                    substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2) rating_state_code,  
                    hiroc_get_province_name(substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2), 'PROVINCE_CODE', 'L') rating_state_name,  
                    hiroc_get_provicne_pol_prefix(substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2),p.policy_type_code) rating_prov_pol_prefix,   
                    nvl(r.risk_cls_used_to_rate,pth.peer_groups_code) rating_peer_group_code,  
                    hiroc_get_lookup_desc('PEER_GROUP',nvl(r.risk_cls_used_to_rate,pth.peer_groups_code),'L')  rating_peer_group_name,   
                    pth.policy_term_history_pk,   
                    pth.term_base_record_fk,   
                    to_char(pth.effective_from_date,'yyyy') term_effective_year,   
                    c.coverage_pk,   
                    c.coverage_base_record_fk,   
                    pc.coverage_code,   
                    c.product_coverage_code,   
                    pc.long_description,   
                    pp.coverage_component_code,  
                    c.effective_from_date,   
                    c.effective_to_date,  
                    cls.coverage_code coverage_class_code,   
                    cls.coverage_long_desc coverage_class_long_desc,   
                    decode(pp.coverage_component_code ,'GROSS',cls.exposure_unit,null) exposure_unit, --hiroc_get_expos_units_by_cov(c.coverage_pk,pc.coverage_code,c.effective_from_date,c.effective_to_date) exposure_unit,   
                    decode(pp.coverage_component_code ,'GROSS',cls.number_of_patient_day,null) number_of_patient_day,   
                    pth.effective_from_date  term_eff_from_date,   
                    pth.effective_to_date term_eff_to_date,    
                    pp.premium_amount premium_amount,    
                    (case when (pc.coverage_code in ('CP','MC1','MC2','MC3','MC4','HR','F') or pc.coverage_code like 'ST%') and  
                                  pp.coverage_component_code != 'RISKMGMT' then     
                            (nvl(pp.premium_amount,0))  
                        else  
                            0  
                    end) primary_premium,   
                    (hiroc_get_risk_units(hiroc_get_provicne_pol_prefix(substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2),p.policy_type_code)-- rating_prov_pol_prefix  
                                        ,nvl(r.risk_cls_used_to_rate,pth.peer_groups_code) -- rating_peer_group_code  
                                        ,cls.coverage_code --coverage_class_code  
                                        ,decode(pp.coverage_component_code ,'GROSS',cls.exposure_unit,null)  
                                        ,pp.premium_amount  
                                        ,(case when (pc.coverage_code in ('CP','MC1','MC2','MC3','MC4','HR','F') or pc.coverage_code like 'ST%') and  
                                                      pp.coverage_component_code != 'RISKMGMT' then     
                                                (nvl(pp.premium_amount,0))  
                                            else  
                                                0  
                                         end)  -- primary_premium  
                                        ,p.policy_type_code           
                                        ,trunc(pth.effective_to_date))) risk_units  
             from     proddw_mart.rmv_territory_makeup tm,  
                      proddw_mart.rmv_premium_class_makeup pcm,  
                      proddw_mart.rmv_product_coverage pc,  
                      proddw_mart.rmv_coverage c,  
                      proddw_mart.rmv_risk r,  
                      proddw_mart.rmv_policy_term_history pth,  
                      proddw_mart.rmv_policy p,  
                      proddw_mart.rmv_transaction_log tl,  
                      proddw_mart.rmv_policy_premium pp,  
                      (select  /* +rule */  
                               p.policy_no,  
                               p.policy_start_date,  
                               p.policy_end_date,   
                               r.risk_pk,  
                               r.risk_description,  
                               c.coverage_pk,  
                               c.parent_coverage_base_record_fk,  
                               pc.parent_product_covg_code,  
                               pc.coverage_code,  
                               pc.short_description coverage_short_desc,   
                               pc.long_description coverage_long_desc,  
                               c.exposure_unit,  
                               pc.exposure_basis_code,  
                               c.number_of_patient_day,  
                               p.policy_start_date policy_effective_date,  
                               p.policy_end_date policy_expiry_date,  
                               c.effective_from_date,  
                               c.effective_to_date,  
                               to_char(c.effective_from_date,'YYYY') class_eff_year  
                        from   proddw_mart.odwr_coverage_only      c  
                              ,proddw_mart.odwr_product_coverage   pc  
                              ,proddw_mart.odwr_risk               r  
                              ,proddw_mart.odwr_policy             p  
                        where  pc.code                 = c.product_coverage_code  
                          and  pc.parent_product_covg_code is not null                 -- coverage classes only  
                          and  r.risk_pk = c.risk_base_record_fk  
                          and  c.accounting_to_date = to_date('1/1/3000','mm/dd/yyyy') -- only open records  
                          and  c.base_record_b = 'N'  
                          and  p.base_record_b = 'N'  
                          and  p.policy_pk = r.policy_fk  
                          and  p.accounting_to_date = to_date('1/1/3000','mm/dd/yyyy')  -- only open records  
                       group by p.policy_no,  
                               p.policy_start_date,  
                               p.policy_end_date,   
                               r.risk_pk,  
                               r.risk_description,  
                               c.coverage_pk,  
                               c.parent_coverage_base_record_fk,  
                               pc.parent_product_covg_code,  
                               pc.coverage_code,  
                               pc.short_description, -- coverage_short_desc,   
                               pc.long_description, -- coverage_long_desc,  
                               c.exposure_unit,  
                               pc.exposure_basis_code,  
                               c.number_of_patient_day,  
                               p.policy_start_date, -- policy_effective_date,  
                               p.policy_end_date, -- policy_expiry_date,  
                               c.effective_from_date,  
                               c.effective_to_date,  
                               to_char(c.effective_from_date,'YYYY')-- class_eff_year  
                      ) cls  
                where    tm.risk_type_code = r.risk_type_code  
                and        tm.county_code = r.county_code_used_to_rate  
                and        tm.effective_from_date <= pp.rate_period_from_date  
                and        tm.effective_to_date   >  pp.rate_period_from_date  
                and        pcm.practice_state_code (+) = r.practice_state_code  
                and        pcm.risk_class_code (+) = r.risk_cls_used_to_rate  
                and        nvl(pcm.effective_from_date, pp.rate_period_from_date) <= pp.rate_period_from_date  
                and        nvl(pcm.effective_to_date, to_date('01/01/3000','mm/dd/yyyy')) > pp.rate_period_from_date  
                and        pc.code = c.product_coverage_code  
                and        c.base_record_b = 'N'  
                and        ( c.record_mode_code = 'OFFICIAL'  
                         and (c.closing_trans_log_fk is null or  
                              c.closing_trans_log_fk != tl.transaction_log_pk)  
                         or c.record_mode_code = 'TEMP'  
                         and c.transaction_log_fk = tl.transaction_log_pk )  
                and   c.parent_coverage_base_record_fk is null  
                and        c.effective_from_date  <  c.effective_to_date  
                and        c.effective_from_date  <= pp.rate_period_from_date  
                and        c.effective_to_date    >  pp.rate_period_from_date  
                and   c.accounting_from_date <= tl.accounting_date  
                and   c.accounting_to_date   >  tl.accounting_date  
                and        c.coverage_base_record_fk=pp.coverage_fk  
                and        r.base_record_b = 'N'  
                and        ( r.record_mode_code = 'OFFICIAL'  
                        and (r.closing_trans_log_fk is null or  
                             r.closing_trans_log_fk != tl.transaction_log_pk)  
                        or r.record_mode_code = 'TEMP'  
                        and r.transaction_log_fk = tl.transaction_log_pk )  
                and        r.effective_from_date  <  r.effective_to_date  
                and        r.effective_from_date  <= pp.rate_period_from_date  
                and        r.effective_to_date    >  pp.rate_period_from_date  
                and   r.accounting_from_date <= tl.accounting_date  
                and   r.accounting_to_date   >  tl.accounting_date  
                and         r.risk_base_record_fk = pp.risk_fk  
                and        pth.base_record_b = 'N'  
                and        ( pth.record_mode_code = 'OFFICIAL'  
                        and (pth.closing_trans_log_fk is null or  
                             pth.closing_trans_log_fk != tl.transaction_log_pk)  
                        or pth.record_mode_code = 'TEMP'  
                        and pth.transaction_log_fk = tl.transaction_log_pk )  
                and        pth.accounting_from_date <= tl.accounting_date  
                and        pth.accounting_to_date   >  tl.accounting_date  
                and        pth.term_base_record_fk = pp.policy_term_fk  
                and   p.policy_pk = pp.policy_fk  
                and        tl.transaction_log_pk  =  pp.transaction_log_fk  
                and   pp.active_premium_b = 'Y'  
                and        pp.rate_period_type_code in ('CS_PERIOD','SR_PERIOD')  
                and        pp.rate_period_to_date > pp.rate_period_from_date  
                and tl.accounting_date <= sysdate   
                and p.policy_cycle_code = 'POLICY'  
                and substr(p.policy_no,1,1) <> 'Q'  
                and tl.transaction_log_pk = (select max(pp.transaction_log_fk)  
                                               from proddw_mart.rmv_policy_premium pp,proddw_mart.rmv_transaction_log tl2  
                                              where pth.term_base_record_fk = pp.policy_term_fk  
                                                and pp.transaction_log_fk = tl2.transaction_log_pk  
                                                and tl2.accounting_date <= sysdate )    
                 and p.policy_type_code in ('LIABCRIME','MIDWIFE')    
                 and pth.accounting_to_date =  to_date('01/01/3000','mm/dd/yyyy') --<<<*******  eliminates duplicates  
                 and p.policy_no = cls.policy_no  
            --     and r.risk_pk = cls.risk_pk  
                 and c.coverage_base_record_fk = cls.parent_coverage_base_record_fk(+)  
                 and  cls.effective_from_date < pth.effective_to_date -- from date less than period end date  
                 and  cls.effective_to_date   > pth.effective_from_date -- to date greater than period start date  
                 and  cls.policy_effective_date   < pth.effective_to_date -- from date less than period end date  
                 and  cls.policy_expiry_date     > pth.effective_from_date -- to date greater than period start date  
           group by pp.policy_fk,  
                    pp.transaction_log_fk,  
                    p.policy_no,  
                    p.policy_type_code,   
                    pp.risk_fk,   
                    r.risk_base_record_fk,   
                    r.entity_fk,  
                    substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2), -- rating_state_code,  
                    r.county_code_used_to_rate,  
                    pth.issue_state_code,  
                    nvl(r.risk_cls_used_to_rate,pth.peer_groups_code) , --  rating_peer_group_code,  
                    r.risk_cls_used_to_rate,  
                    pth.peer_groups_code,  
                    pth.policy_term_history_pk,   
                    pth.term_base_record_fk,   
                    to_char(pth.effective_from_date,'yyyy'), --term_effective_year,   
                    c.coverage_pk,   
                    c.coverage_base_record_fk,   
                    pc.coverage_code,   
                    c.product_coverage_code,   
                    pc.long_description,   
                    pp.coverage_component_code,  
                    c.effective_from_date,   
                    c.effective_to_date,  
                    cls.coverage_code, -- coverage_class_code,   
                    cls.coverage_long_desc, -- coverage_class_long_desc,   
                    decode(pp.coverage_component_code ,'GROSS',cls.exposure_unit,null),-- exposure_unit,   
                    decode(pp.coverage_component_code ,'GROSS',cls.number_of_patient_day,null), -- number_of_patient_day,   
                    pth.effective_from_date, --term_eff_from_date,   
                    pth.effective_to_date, --, --term_eff_to_date,    
                    pp.premium_amount ;Edited by: BluShadow on 27-Jun-2012 16:12
    added {noformat}{noformat} tags for readability.  PLEASE READ {message:id=9360002} AS PREVIOUSLY REQUESTED!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           &

  • Insert statement will not work if select statement has less number of colum

    Hi,
    One of my thread is already resolved on the following URL : unable to insert rows into the table
    DROP TABLE TEMP;
    CREATE TABLE TEMP AS SELECT * FROM CASE_101 WHERE 1=2;
    DECLARE
    S VARCHAR2(200);
    STMT VARCHAR2(500);
    begin
    for C in (select TABLE_NAME INTO S from USER_TABLES where TABLE_NAME like 'CASE%' TABLE_NAME NOT like '%OLD' and Num_ROWS > 0 order by TABLE_NAME) loop
    STMT := 'INSERT INTO TEMP SELECT * FROM ';
    STMT:=STMT || C.TABLE_NAME;
    EXECUTE IMMEDIATE STMT;
    dbms_output.put_line(c.table_name);
    end loop;
    end;
    i am facing now some different; almost all the tables have same number of columns except in few of tables have some additional columns. As above i am creating a table "TEMP" who has highest column temp(by doing some manual process). The table who has less columns than "TEMP" table : Insert statement will not work. 'INSERT INTO TEMP SELECT * FROM less_columns_table_name'.
    Please let me know , how can i execute proper way.
    Thanks.
    Best Regards
    Arshad

    user13360241 wrote:
    Hi,
    One of my thread is already resolved on the following URL : unable to insert rows into the table
    DROP TABLE TEMP;
    CREATE TABLE TEMP AS SELECT * FROM CASE_101 WHERE 1=2;
    DECLARE
    S VARCHAR2(200);
    STMT VARCHAR2(500);
    begin
    for C in (select TABLE_NAME INTO S from USER_TABLES where TABLE_NAME like 'CASE%' TABLE_NAME NOT like '%OLD' and Num_ROWS > 0 order by TABLE_NAME) loop
    STMT := 'INSERT INTO TEMP SELECT * FROM ';
    STMT:=STMT || C.TABLE_NAME;
    EXECUTE IMMEDIATE STMT;
    dbms_output.put_line(c.table_name);
    end loop;
    end;
    i am facing now some different; almost all the tables have same number of columns except in few of tables have some additional columns. As above i am creating a table "TEMP" who has highest column temp(by doing some manual process). The table who has less columns than "TEMP" table : Insert statement will not work. 'INSERT INTO TEMP SELECT * FROM less_columns_table_name'.
    Please let me know , how can i execute proper way.
    Thanks.
    Best Regards
    Arshadmore often than not "TEMP" tables are NOT required & are highly inefficient in Oracle.
    Either only specify explicit column in TEMP to get data,
    or provide value for "extra" column in TEMP

  • 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

  • INSERT statement in Java and MS Access

    Hi all,
    can anyone please tell me how to insert data to an MS Access table using JSP i tried INSERT statement of java but it is getting errors saying INSERT statement is wrong. I have no idea about MS access insert statement. i am totally tired of this. Please someone help me.

    Hello,
    MS Sql can cause problems where it goes off standard, however I dont think insert is any different.
    INSERT INTO table_name (column1, column2) VALUES (variable1, variable2)
    Make sure your table and column names are exactly right, Java is case sensitive, so make sure the case is correct also.
    The other common error is if you have a required field in the database that is not populated by your program, so, if for instance there was a column3 in the table for the above example, which was a required field, the sql would fail as there is no data being entered for column3.

  • Using 1million insert statement to create a table

    Dear Expert;
    Lets say someone sent you about 2 million insert statements and you want to use them to insert into a table or create a new table...How do you go about doing so...
    because I tried just highlighting all the insert statement and executing them, however that didnt work in pl/sql developer, it was crashing everytime I did so
    The other way might be to create a loop for them and inserting about 10,000 at a time...but is there a faster way to do it...
    All help is appreciated it..

    user13328581 wrote:
    Dear Expert;
    Lets say someone sent you about 2 million insert statements and you want to use them to insert into a table or create a new table...How do you go about doing so...
    because I tried just highlighting all the insert statement and executing them, however that didnt work in pl/sql developer, it was crashing everytime I did soDo it in SQL*PLUS. It can handle such large files.
    And let it run at night so that other users are not influenced that much by your session.
    You might want to add very few commits somewhere in between. However in case something breaks you then need to know which insert was still executed and which one one.

  • There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.

    I have been looking at my code for hours now and cant figure out what is wrong. The error has kept popping up even when i thought i had fixed everything. maybe a second set of eyes could help me out here. If you could help me out it would be much appreciated.
    USE [ConorsSetKits]
    GO
    CREATE TABLE Customers (
    CustomerID Int NOT NULL IDENTITY(1000,1),
    LastName NChar(30) NOT NULL,
    FirstName NChar(30) NOT NULL,
    Address NChar(50) NOT NULL,
    City NChar(30) NOT NULL,
    State NChar(2) NOT NULL,
    Zip Numeric(5) NOT NULL,
    Email NVarChar(50) NOT NULL,
    DateOfBirth Numeric (4) NOT NULL,
    CONSTRAINT CustomersPK PRIMARY KEY(CustomerID),
    CONSTRAINT ValidZip
    CHECK ( [Zip] LIKE '[0-9][0-9][0-9][0-9][0-9]' ),
    CONSTRAINT ValidState
    CHECK( LEN([State]) = 2),
    CONSTRAINT DateOfBirth
    CHECK ([DateOfBirth] BETWEEN '1920-01-01' AND getdate() - 5844));
    CREATE TABLE Sets (
    SetID Int NOT NULL IDENTITY(1000,1) Primary Key,
    SetName NChar(20) NOT NULL,
    SetType NChar (20) NOT NULL,
    Price Numeric (20) NOT NULL,
    Quantity Numeric (50) NOT NULL,
    CONSTRAINT SetTypeCheck
    CHECK (SetType IN ('Planes','Tanks','Robots','Cars','Helicopters','Boats','Trains','Motorcycles','Jets')),
    CONSTRAINT ValidQuantity 
    CHECK (Quantity >= 0)
    CREATE TABLE Orders (
    OrderID Int NOT NULL IDENTITY(1000,1),
    CustomerID Int NOT NULL,
    OrderDate Date NOT NULL,
    CONSTRAINT CAIntPK PRIMARY KEY(OrderID, CustomerID),
    SET IDENTITY_INSERT dbo.CUSTOMER OFF
    SET IDENTITY_INSERT dbo.Sets OFF
    SET IDENTITY_INSERT dbo.Orders OFF
    SET IDENTITY_INSERT dbo.CUSTOMER ON
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1000, 'Janes', 'Jeffrey', '123 W. Elm St', 'Renton', 'WA', '98055',
    '[email protected]',1985);
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1001, 'Smith', 'David', '813 Tumbleweed Lane', 'Loveland', 'CO', '81201', 
    '[email protected]',1992);
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1015, 'Twilight', 'Tiffany', '88 1st Avenue', 'Langley', 'WA', '98260',
    '[email protected]',1972);
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1033, 'Smathers', 'Fred', '10899 88th Ave', 'Bainbridge Island', 'WA', '98110',
    '[email protected]',1980);
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1034, 'Frederickson', 'Mary Beth', '25 South Lafayette', 'Denver', 'CO', '80201',
    '[email protected]',1970);
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1036, 'Warning', 'Selma', '205 Burnaby', 'Vancouver', 'BC', '80201',
    '[email protected]',1981);
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1037, 'Wu', 'Susan', '105 Locust Ave', 'Atlanta', 'GA', '30322',
    '404', '653-3465', '[email protected]',1971);
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1040, 'Gray', 'Donald','55 Bodega Ave', 'Bodega Bay', 'CA', '94923',
    '[email protected]',1985);
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1041, 'Johnson', 'Lynda', '117 C Street', 'Washington', 'DC', '20003',
    '[email protected]',1969);
    INSERT INTO Customers
    (CustomerID, LastName, FirstName, Address, City, State, Zip,
    Email, DateOfBirth)
    VALUES (
    1051, 'Wilkens', 'Chris', '87 Highland Drive', 'Olympia', 'WA', '98508',
    '[email protected]',1994); 
    SET IDENTITY_INSERT dbo.CUSTOMER OFF
    SET IDENTITY_INSERT dbo.Sets ON
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1000, 'MysterySet1','Planes',$29.99,10);
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1001, 'MysterySet2','Planes',$19.99,10);
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1002, 'MysterySet4','Tanks',$39.99,10);
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1003, 'MysterySet3','Robots',$19.99,10);
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1004, 'MysterySet5','Cars',$29.99,10);
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1005, 'MysterySet6','Boats',$29.99,10);
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1006, 'MysterySet7','Trains',$39.99,10);
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1007, 'MysterySet8','Motorcycles',$9.99,10);
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1008, 'MysterySet9','Helicopters',$29.99,10);
    INSERT INTO Sets
    (SetID, SetName, SetType, Price, Quanity)
    VALUES (
    1009, 'MysterySet10','Jets',$29.99,10);
    SET IDENTITY_INSERT dbo.Sets OFF
    SET IDENTITY_INSERT dbo.Orders ON
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1000, '2012-12-12');
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1000, '2013-12-30');
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1005, '2013-08-30');
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1004, '2013-12-30');
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1004, '2013-08-31');
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1004, '2014-03-25');
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1002, '2012-11-14');
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1001, '2012-11-14');
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1001, '2013-01-05');
    INSERT INTO Orders 
    (OrderID, OrderDate)
    VALUES 
    (1006, '2012-06-22');
    SET IDENTITY_INSERT dbo.Orders OFF

    Price Numeric (20) NOT NULL,
    I do not think you understand this datatype?  Go look at the values you are attempting to insert into this column.  For example, "$29.99".  After the insert, what value is actually stored in that column? 
    DateOfBirth Numeric (4) NOT NULL,
    No. Just No.  Either change the column name to faithfully represent what values you intend to store (and apply the appropriate constraints) or change the datatype and the values that you intend to store to match the column name.  And the constraint
    that you do have:
     CONSTRAINT DateOfBirth
     CHECK ([DateOfBirth] BETWEEN '1920-01-01' AND getdate() - 5844));
    is both logically suspect and syntactically wrong. First, the upper boundary will be computed as 1999-04-29 15:50:21.670.  But, of course, your column is a whole number of no more than 4 digits.  The same issue applies to your lower boundary. 
    A simple select statement will show you those errors
    select cast('1920-01-01' as numeric(4)), getdate() - 5844, cast(getdate() - 5844 as numeric(4));
    An insert statement fails with the same error.  Because, of course, your boundary values must actually be converted to numeric(4) in order to compare them against the value contained in the column.   Generally, you can convert from
    string to numeric - IF the content of the string actually contains a value that is numeric and can be converted into the specific type needed.  Not so in this case.  Is this 16 year period (5844 days) significant for some reason?  You should
    document it here in your DDL with a comment, because it is unlikely to be documented (and kept current) anywhere else. 
    And lastly, your script has:
    SET IDENTITY_INSERT dbo.CUSTOMER OFF
    That is not the name of your table, and therefore that statement also fails.  The table name you used is plural. 

  • ROWCOUNT in BULK Insert Statement

    Hi,
    I'm using in a BULK INSERT statement in a PL/SQL procedure and after execution of the SQL statement,I need to capture the row count.
    Same is the case for UPDATE.
    The Example code is as mentioned below:
    INSERT INTO TBL1
    (SELECT VAL1,VAL2 FROM TBL2)
    No. of rows inserted needs to be retrieved after execution of this SQL.
    Please let me know if there is any way to do it.
    Thanks.

    SQL> create table emp as select * from scott.emp where 1 = 0 ;
    Table created.
    SQL> set serveroutput on
    SQL> begin
      2    insert into emp select * from scott.emp ;
      3    dbms_output.put_line('Count='||SQL%RowCount) ;
      4  end ;
      5  /
    Count=14
    PL/SQL procedure successfully completed.
    SQL>

  • Use NEXTVAL in an insert statement Part II

    db - 10g
    I am asking this question out of curiosity.
    I posted a question and recieved a successful answer at the following address on this forum;
    Use NEXTVAL in an insert statement
    The following insert statement uses a sequence to create an arbitrary number for each null record. The problem is, the sequence is firing regardless of the condition being true or false (but it is working in that it only inserts values when the condition is true). The result is the sequence appears to increment each time it loops through the cursor and so the first arbitrary number to be inserted is not 1001 but some other higher number.
    INSERT INTO psp_trees
    ( plot_id
    , tree_name
    , species_code)
    VALUES
    ( get_plot_id
    , c1.treenum          
    , c1.species
    ) RETURNING tree_id INTO get_tree_id;   I have gotten around the issue by removing the sequence from the insert statement and placing it outside the cursor loop as an update statement.
          UPDATE psp_trees
             SET tree_name = to_char(tree_arbitrary_name_seq.nextval)
           WHERE tree_name IS NULL;Is there anyway to get the sequence to only fire in the insert statement when the condition is true.
    This is the complete anonymous block for your reference;
    DECLARE p_access_num NUMBER;
    col_access_var VARCHAR2(30);
    type number_ptb IS table OF VARCHAR2(4000);
    p_access_nam number_ptb;
    get_plot_measurement_id NUMBER;
    update_plot_measurements VARCHAR2(4000);
    get_tree_id NUMBER;
    get_plot_id NUMBER;
    BEGIN
        p_access_num := 6;
        p_access_nam := number_ptb();
        p_access_nam.extend(7);
        p_access_nam(1) := 535;
        p_access_nam(2) := 548;
        p_access_nam(3) := 898;
        p_access_nam(4) := 544;
        p_access_nam(5) := 551;
        p_access_nam(6) := 724;
        FOR loop_int IN 1 .. p_access_num
        LOOP
          col_access_var := p_access_nam(loop_int);
          -- 1. Initiate insert process by getting PK from psp_plots.
          SELECT plot_id INTO get_plot_id FROM psp_plots WHERE plot_name = col_access_var;    
          -- 2. Insert records into psp_plot_measurements and keep relationship with psp_plots with variable get_plot_id.
          --    and get primary key value of psp_plot_measurements to insert into psp_tree_measurements during loop process.
          INSERT INTO psp_plot_measurements (plot_id) VALUES (get_plot_id) RETURNING plot_measurement_id INTO get_plot_measurement_id;   
          -- 3. Update record created at point 2.
          UPDATE psp_plot_measurements
             SET measurement_date    = (SELECT DISTINCT date_ FROM pspdata)
               , codominant_height   = (SELECT DISTINCT height_codom FROM pspdata)
               , assessor            = (SELECT DISTINCT assessor FROM pspdata)
           WHERE plot_measurement_id = col_access_var
          -- 4. Open cursor to insert rows one at a time and maintain relationships between related tables.
          FOR c1 IN (SELECT treenum
                          , dbhob
                          , treecomments
                          , species
                       FROM pspdata
                      WHERE plotnumber = col_access_var
                        AND date_ IS NOT NULL)     
              LOOP   
                -- 5. Insert record into psp_trees
                --    and get primary key value of psp_trees to insert into psp_tree_measurements.
                INSERT INTO psp_trees
                ( plot_id
                , tree_name
                , species_code)
                VALUES
                ( get_plot_id
                , c1.treenum
                --, NVL(c1.treenum , to_char(tree_arbitrary_name_seq.nextval))
                --, (CASE WHEN c1.treenum IS NULL THEN to_char(tree_arbitrary_name_seq.nextval) ELSE c1.treenum END)
                , c1.species
                ) RETURNING tree_id INTO get_tree_id;   
                -- 6. Insert records into psp_tree_measurements and keep relationship with psp_trees with variable get_tree_id.
                INSERT INTO psp_tree_measurements
                ( plot_measurement_id
                , tree_id
                , dbhob          
                , comments
                VALUES
                ( get_plot_measurement_id
                , get_tree_id
                , c1.dbhob
                , c1.comment
              END LOOP;         
      END LOOP; 
          -- 7. Update null columns with arbitrary number.
          UPDATE psp_trees
             SET tree_name = to_char(tree_arbitrary_name_seq.nextval)
           WHERE tree_name IS NULL;
    END;
    /Edited by: benton on Sep 6, 2011 1:53 PM

    Or use a function (I'll use dbms_xml.getxml):
    SQL> create sequence s_seq nocache
    Sequence created.
    SQL> select case when mod (level, 2) = 0
                then extractvalue(dbms_xmlgen.getxmltype('select s_seq.nextval from dual'), '//text()')
                else '0' end col1
              from dual connect by level < 20
    COL1                                                                           
    0                                                                              
    1                                                                              
    0                                                                              
    2                                                                              
    0                                                                              
    3                                                                              
    0                                                                              
    4                                                                              
    0                                                                              
    5                                                                              
    0                                                                              
    6                                                                              
    0                                                                              
    7                                                                              
    0                                                                              
    8                                                                              
    0                                                                              
    9                                                                              
    0                                                                              
    19 rows selected.
    SQL> select sequence_name, last_number from user_sequences where sequence_name = 'S_SEQ'
    SEQUENCE_NAME                  LAST_NUMBER
    S_SEQ                                   10
    1 row selected.

  • Insert statement stores multiple records...

    Hi there. ive been having trouble with my insert statements. for some reason unknown to me, the following code creates two entries in the same table:
    SELECT product_id_sequence.nextval
    into products.prod_id
    from dual;
    INSERT INTO PRODUCTS VALUES('PRD'|| :products.prod_id,:products.prod_status, :products.store_id);
    INSERT INTO PRODUCT_PHONE VALUES('PRD' || :products.prod_id, :PHONE.phone_model, :phone.phone_price, :phone.phone_brand,
    :phone.phone_description);
    commit;
    The result of the sql statement:
    TABLE PRODUCTS
    PRD10000119 | In Stock | STR100000005
    10000119 | In Stock | STR100000005
    As you can see, the first 3 letters of the product_id are not repeated in the second record. The same is also repeated in the product_phone table. i am not sure why this is the case. please help
    Message was edited by:
    user597970

    Hi,
    Do you have the two products and product_phone blocks on your form ?
    are the database blocks matching tables in your db?
    could explain how you built the form?
    I think that your form has two database blocks, which will perform DML actions as this is a built in funcionality in forms.
    From your code, the inserts are performed ok, and the commit after, commits the data on screen as well, hence the second entry.
    Please take alook at this thread, for suggestions on forum usage:
    http://forums.oracle.com/forums/ann.jspa?annID=432
    Regards,
    Hugo

  • Use of the "updlock" hint with update and insert statements

    I have inherited some stored procedures and am trying to figure out why the developers decided to use the "updlock" hint on many of the update and insert statements. I have looked around everywhere and have found only one explanation of why "update...with
    (updlock)" can be useful, namely when a table has no clustered index:
    http://www.sqlnotes.info/2012/10/10/update-with-updlock/ I have found nothing yet that mentions why "insert into...with (updlock)" might be used. I understand why the hint
    might be useful on select statements in some cases, but if all of the tables have clustered indexes, is there any good reason to use it on update and insert statements?
    Thanks,
    Ron
    Ron Rice

    This form of deadlock error can occur on a table which has a clustered index.
    If you are doing updates on a table which has a clustered index and that table also has a nonclustered index and the nonclustered index is used to find the row to update you can see this type of deadlock.  For example create a table with a clustered
    primary key index and a nonclustered index by running
    Create Table Foo(PK int primary key identity, OtherKey varchar(10), OtherData int);
    go
    Insert Foo Default Values;
    go 10000
    Update Foo Set OtherKey = 'C' + Cast(PK As varchar(10))
    Create Unique Index FooIdx On Foo(OtherKey);
    That creates a table with 10000 rows, a clustered index and a nonclustered index.  Then run
    Begin Transaction
    Update Foo Set OtherData = 1 Where OtherKey = 'C5'
    That will use the FooIdx index to find the row that needs to be updated.  It will get a U lock on the index row in the FooIdx index, then an X lock on the row in the clustered index, update that row, then free the U lock on FooIdx, but keep the X lock
    on the row in the clustered index.  (There is other locking going on, but to simplify things, I'm only showing the locks that lead to the deadlock).
    Then in another window, run
    Begin Transaction
    Update Foo Set OtherData = 2 Where OtherKey = 'C5'
    This will get a U lock on the index row in the FooIdx index, then try to get an X lock on the row in the clustered index.  But that row is already exclusively locked, so this second window will wait holding a U lock on FooIdx row and is waiting for
    an X lock on the clustered index row.
    Now go back to the first window and run
    Update Foo Set OtherData = 3 Where OtherKey = 'C5'
    This will once again try to get the U lock on the FooIdx row, but it is blocked by the U lock the second window holds.  Of course the second window is blocked by the X lock on the clustered index row and you have a deadlock.
    All that said, I certainly do not routinely code my updates with UPDLOCK.  I try to design databases and write code so that deadlocks will be rare without holding excessive locks.  The more locks you hold and the longer you hold them, the more
    blocking you will get and the slower your system will run.  So I write code that if a deadlock exception occurs, it is properly handled.  Then if too many deadlocks occur, that is the time to go back to the code to see what changes are needed to
    decrease the number of deadlocks (one way to do that may be to get locks earlier and/or hold them longer. 
    But I wouldn't worry much about this form of deadlock.  It is, in my experience, vary rare.  I don't recall ever seeing it in a production environment.
    Tom

  • How to assign value from insert statement to variable from a trigger

    Hi,
    I got this really annoying problem and I don't know if I am doing it correctly.
    I have a BEFORE INSERT trigger on a table. When someone executes an insert statement I want to grab the value of a column from that statement and assign it to a variable and then do stuff with it. I'm stuck on the assignment.. look below..
    CREATE OR REPLACE TRIGGER CARS.geotest2_trigger
    BEFORE INSERT ON CARS.GEO_TEST2
    FOR EACH ROW
    DECLARE
    v_chainkey nchar(32);
    v_chainkey2 nchar(32);
    not_exists EXCEPTION;
    BEGIN
    :NEW.CHAINKEY := v_chainkey;
    SELECT GEO_TEST.CHAINKEY INTO v_chainkey2 FROM GEO_TEST WHERE GEO_TEST.CHAINKEY = v_chainkey;
    IF v_chainkey2 = '' or v_chainkey2 is null THEN
    RAISE not_exists;
    ELSE
    INSERT INTO GEO_TEST2 VALUES(:NEW.CHAINKEY, :NEW.BLA, :NEW.FOO);
    END IF;
    EXCEPTION
    WHEN not_exists THEN
    RAISE_APPLICATION_ERROR(-20010, 'Chainkey does not exist in parent table GEO_TEST');
    END;
    I keep getting this error
    Error: ORA-04098: trigger 'CARS.GEOTEST2_TRIGGER' is invalid and failed re-validation
    SQLState: 42000
    ErrorCode: 4098

    It isn't assigning because v_chainkey is not at the left hand side of the assignment statement.
    test@ORA10G>
    test@ORA10G>
    test@ORA10G> declare
      2    x  number := 5;
      3    y  number;
      4  begin
      5    x := y; -- does not assign anything to y; assigns NULL to x,
      6            -- because y is NULL at this point
      7            -- so, essentially the value 5 of x is *LOST* now
      8    dbms_output.put_line('x = '||x);
      9  end;
    10  /
    x =
    PL/SQL procedure successfully completed.
    test@ORA10G>
    test@ORA10G>
    test@ORA10G>In any case, here's what you are probably looking for:
    test@ORA10G>
    test@ORA10G> --
    test@ORA10G> drop table geo_test;
    drop table geo_test
    ERROR at line 1:
    ORA-00942: table or view does not exist
    test@ORA10G> drop table geo_test2;
    drop table geo_test2
    ERROR at line 1:
    ORA-00942: table or view does not exist
    test@ORA10G>
    test@ORA10G> create table geo_test (chainkey nchar(32));
    Table created.
    test@ORA10G> insert into  geo_test (chainkey) values ('a');
    1 row created.
    test@ORA10G> insert into  geo_test (chainkey) values ('');
    1 row created.
    test@ORA10G>
    test@ORA10G> create table geo_test2 (chainkey nchar(32), bla number(1), foo number(1));
    Table created.
    test@ORA10G>
    test@ORA10G>
    test@ORA10G> CREATE OR REPLACE TRIGGER geotest2_trigger
      2  BEFORE INSERT ON GEO_TEST2
      3  FOR EACH ROW
      4  DECLARE
      5    v_chainkey2  nchar(32);
      6    not_exists   EXCEPTION;
      7  BEGIN
      8    SELECT GEO_TEST.CHAINKEY INTO v_chainkey2 FROM GEO_TEST WHERE nvl(GEO_TEST.CHAINKEY,'~') = nvl(:new.chainkey,'~');
      9    IF v_chainkey2 is null THEN
    10      RAISE not_exists;
    11    END IF;
    12  EXCEPTION
    13    WHEN not_exists THEN
    14      RAISE_APPLICATION_ERROR(-20010, 'Chainkey does not exist in parent table GEO_TEST');
    15  END;
    16  /
    Trigger created.
    test@ORA10G>
    test@ORA10G> --
    test@ORA10G> insert into geo_test2 (chainkey,bla,foo) values ('b',1,1);
    insert into geo_test2 (chainkey,bla,foo) values ('b',1,1)
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at "TEST.GEOTEST2_TRIGGER", line 5
    ORA-04088: error during execution of trigger 'TEST.GEOTEST2_TRIGGER'
    test@ORA10G>
    test@ORA10G> --
    test@ORA10G> insert into geo_test2 (chainkey,bla,foo) values (null,1,1);
    insert into geo_test2 (chainkey,bla,foo) values (null,1,1)
    ERROR at line 1:
    ORA-20010: Chainkey does not exist in parent table GEO_TEST
    ORA-06512: at "TEST.GEOTEST2_TRIGGER", line 11
    ORA-04088: error during execution of trigger 'TEST.GEOTEST2_TRIGGER'
    test@ORA10G>
    test@ORA10G> --
    test@ORA10G> insert into geo_test2 (chainkey,bla,foo) values ('a',1,1);
    1 row created.
    test@ORA10G>
    test@ORA10G>
    test@ORA10G>pratz
    I think the sole purpose of that "not_exists" exception is this -
    If you try to insert a NULL value for GEO_TEST2.CHAINKEY, then this trigger will throw an error even if at least one NULL value exists in GEO_TEST.CHAINKEY column.
    Not sure if that's something that you wanted.
    Message was edited by:
    pratz

Maybe you are looking for

  • Connect apple tv to imac

    How can I connect an Apple TV to my iMac mid 2011, 21.5 inch? Thanks a ton for your help

  • Help with Re-Installing Itunes on Windows XP

    Somehow my Itunes was removed from my computer. I tried re-installing it by going on apple.com and downloading it. It starts to guide me through the re-installation process but a series of error messages come up disrupting the installation process: "

  • Unable to upgrade to EFI 1.9 on MacBookPro6,2 model

    I've downloaded the EFI Firmware Update 1.9 from support.apple.com/kb/DL1098 and verified that my main HD is GUID Partitioned and that I have the correct file for my model based on info in system profile. However, when I mount the disk image and try

  • IOS 4.3.1 (8G4) bug? "Flash is Disabled"

    I bet you thought I meant Adobe Flash, huh? Well that a whole other discussion. I think I found a bug in the firmware, that involved the camera flash. Overall, I really don't think it is significant... more interesting. Repeatable steps to make the i

  • PO Fax output issue

    Hi, We have configured FAX output for PO. The fax  output is being processed successfully. We have issue in which if a user processes fax output and its sent successfully from ECC but there is error at the fax machine. In this case, User might think