TIPS(53) : DECODE를 이용한 DATE INSERT 시에 잘못된 값이 들어가는 경우.

제품 : ORACLE SERVER
작성날짜 : 2002-11-06
TIPS(53) : DECODE를 이용한 DATE INSERT 시에 잘못된 값이 들어가는 경우
=====================================================================
Purpose
decode를 사용하는 date data type의 처리에서는 가끔 예기치 않은
오류가 발생된다. 예를 들면 2000년을 insert를 하였는데 실제 값은
1900년이 들어가게 되는 문제이다. 이것은 사용자를 매우 당황하게
만드는데 이런 경우에 대해 확인하고 조치하는 방법을 살펴보자.
Problem Description
1. nls_date_format을 'yy-mon-dd'로 하였을 경우
SQL> ALTER SESSION SET NLS_DATE_FORMAT='YY-MON-DD';
SQL> CREATE TABLE TABDATE(COLDATE DATE);
SQL> INSERT INTO TABDATE(COLDATE)
SELECT DECODE('1','0',NULL,'1',(TO_DATE('200511','RRRRMM')))
FROM DUAL;
SQL> SELECT TO_CHAR(COLDATE,'YYYY-MM-DD') FROM TABDATE;
TO_CHAR(CO
1905-11-01 -- 2005년이 들어가 있어야 하는데 오동작을 했다.
2. nls_date_format을 'yyyy-mon-dd'로 하였을 경우
SQL> ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MON-DD';
SQL> INSERT INTO TABDATE(COLDATE)
SELECT DECODE('1','0',NULL,'1',(TO_DATE('200511','RRRRMM')))
FROM DUAL;
SQL> SELECT TO_CHAR(COLDATE,'YYYY-MM-DD') FROM TABDATE;
TO_CHAR(CO
1905-11-01
2005-11-01 -- 정상적인 값이 들어와 있다.
3. 문제 설명
어떻게 이런 문제가 발생하는가?
이것은 dbms가 decode를 처리하는 내부적인 절차에 의해 벌어지는 것으로
당연한 현상이다. decode를 처리할 경우 decode 안의 값이 to_date로
처리되기 이전에 varchar2로 값을 넘겨 받아서 그 결과값으로 to_date
함수에 넘겨저서 처리하게 된다.
그런데 이 경우에 to_date 함수를 처리하기 전에 data의 conversion에
이용되는 것이 시스템의 default NLS_DATE_FORMAT 값인 것이다.
그러므로, 이 값의 년도 처리가 두 자리로 되어 있을 경우 년도를 두자리
만을 처리하여 varchar2 값으로 넘기게 되고 이것을 to_date 함수를
이용하여 처리하게 되므로 우리가 예상치 못한 값이 나오게 되는 것이다.
실제 SQL이 다음과 같으면
SELECT to_char(to_date('0511','yyMM'),'yyyymmdd') FROM DUAL;
결과 값은 19051101로나오게 된다.
Solution Description
이 문제는 NLS_DATE_FORMAT의 년도가 두 자리로 지정된 경우에
decode 함수를 사용하는 date data는 오동작을 할 가능성이 있다는 것이다.
이에 대한 해결 방법은 nls_date_format의 년도를 네 자리로 지정해 주는 것이다.
이에는 세 가지 방법이 있을 것이다.
1. alter session set nls_date_format='yyyy-mm-dd';
2. 환경변수의 nls_date_format을 변경하기.
3. database 내의 nls_date_format를 변경하기.
Reference Documents
none

Similar Messages

  • Looking for some tips on Decoding date. TX

    HI,I still have problem with this decode. I need to count students group by their region on each month. The output should be
    COUNTRY OCT NOV DEC .....
    USA 5 20 30
    CAN 100 1 0
    MEX 10 20 30
    The date format is 5/19/2007
    This is my code: and thanks for your help
    WITH Q AS (SELECT DISTINCT A.STDID, A.NUMBER, A.ADMIT
    FROM PROG A
    JOIN CITIZEN B ON A.STDID = B.STDID
    JOIN REGION_TBL C ON C.REGION = B.REGION
    AND A.NUMBER = 'PS'
    AND A.ADMIT IN ('2007','2008'))
    SELECT J.REGION, I.DESCR,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '09', 1, 0))) SEP_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '10', 1, 0)))OCT_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '11', 1, 0)))NOV_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '12', 1, 0)) )DEC_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '1', 1, 0)) )JAN_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '2', 1, 0)) )FEB_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '3', 1, 0)) )MAR_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '4', 1, 0)) )ARL_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '5', 1, 0)) )MAY_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '6', 1, 0)) )JUN_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '7', 1, 0)) )JUL_TOTAL,
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '8', 1, 0)) )AUG_TOTAL
    FROM CITIZEN J
    JOIN PROG L ON J.STDID = L.STDID
    JOIN Q ON J.STDID = Q.STDID
    AND Q.NUMBER = J.NUMBER
    GROUP BY J.REGION, I.DESCR

    SUM(DECODE(TO_CHAR(L.ACTION_DT,'YYYY-MM-DD', '09', 1, 0))) SEP_TOTAL,Apart from having brackets in the wrong place you are comparing a date that you are converting to a string in the format YYYY-MM-DD to a string that is 1 or 2 digit number.
    This should be something like
    SUM(DECODE(TO_CHAR(L.ACTION_DT,'MM'),'09',1,0)) as SEP_TOTAL,

  • Customizing data insert from

    I have a data insert from that is solely used to insert data in a database. I am trying to figure out a way to customize it such that a few file get auto filled. I use the form to insert data in a table called maintable. 8 of the 10 field of this maintable filled from different vendor's table(currently i manaully put it). What I like to do is see if I can integrate the vendor's table in the page and write codes to autofill the form that put the data in the maintable. I know maybe a while statement will do it. So if in the form  I input vendor's name and product id. it will get the data from vendor's table and relavent product to fill rest of the field. Any guidance will be greatly appreciated as I am very new to web development and don't have much experince in PHP codes.
    Thanks

    Maybe u can try like this. Assuming you have two inputs in form which I have assigned as below
    $product_id = $_POST['pid'];
    $vendor = $_POST['vendor_name'];
    Then do check for vendor name input.
    if(isset($_POST['vendor_name') && !empty($_POST['vendor_name'])) {
    $query = " SELECT * FROM vendor WHERE vendor_name = '$vendor' ";
    $query2 = mysql_query($query, $databaseName) or die(mysql_error);
    $vendor = mysql_fetch_assoc($query2);
    } else echo 'Vendor name doesn't exists';
    $var = $vendor['var'];
    assign for the rest values u want to store in maintable
    //do insert record
    $insert = INSERT INTO maintable .... VALUES ('$vendor', '$var',.....)

  • Decode date help

    hi all,
    Trying to run a simple decode date check:
    select T1.priority
    , DECODE(T1.submitdate, (greatest(T1.submitdate, '30/06/2007')),'1') as MyCount
    from table1 T1
    my goal is to cross tab this so result will look like:
    PRIORITY TOTAL NEW AS OF 30/06/2007
    HIGH 5 1
    MEDIUM 1 0
    is my decode working correctly with the date range?
    So I want to see for HIGH, are there "NEW" ones since 30/06/2007?
    thanks!

    select T1.priority, count(*) as "Total"
    , CASE WHEN T1.submitdate >= to_date('30/06/2007','DD/MM/YYYY') THEN '1' ELSE '0' END as New
    from table T1
    hmmm, this works now but the results are not summed up??
    PRIORITY TOTAL NEW
    HIGH 1 1
    HIGH 1 0
    HIGH 1 0 .......
    how do I get this?
    PRIORITY TOTAL NEW
    HIGH 3 1

  • Combo Box doesn't persist data insertion settings

    Hi,
    I'm simply trying to setup a combo box that places the selected label into a destination table cell. I've tried about every combination possible to simply add a data insertion series. Please note, I AM clicking the plus button to add it to the list shown to the left of the settings. Unfortunately, everytime I have the series added and I click away from the selected combo box it loses the settings I just provided.
    Has anybody else had these frustrating issues with the combo box component?
    Thank you.

    Greg,
    The combo box component can be a bit fiddly at times. It would help if you let me know which version of Xcelsius you are using.
    In any case if you are simply trying to insert the label to a destination you dont need to bother with the series at all. Try it in this order:
    1) Drag a combo box component
    2) In combo box properties pane and click on the range select button beside Labels
    3) Select the range in your excel sheet that has the labels and click OK
    4) Go back to the properties pane and choose Insertion Type: Label
    5) Click the range select button beside Destination and select a cell
    6) To test it drag a Text -> Label compoent in and point it to the destination cell you selected in step 5.
    7) Preview to see if all is in order
    Let me know how you get on.
    Cheers,
    Ryan

  • SQL server Timeout issue in data insertion

    We are loading data from DB2 database to SQL server using Data flow task. During data insertion in SQL server, we are receiving the below error.
    "An exception has occurred during data insertion, the message returned from the provider is: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding."
    Kindly help to resolve this issue.
    Thanks!!!

    Check the connection timeout property of the source connection.
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/a5571966-b14e-45c6-9ce8-4f5651d3ee00/ado-net-destination-timeout-issue?forum=sqlintegrationservices
    Regards, RSingh

  • TIPS(63) : LONG DATA TYPE의 LENGTH 구하기

    제품 : PL/SQL
    작성날짜 : 1999-04-15
    TIPS(63) : LONG DATA TYPE의 LENGTH 구하기
    =========================================
    PURPOSE
    다음은 function 을 적용할 수 없는 long data type 의 length 를
    구하는 방법을 소개한다.
    Explanation
    Long DataType 에 대해 Length 를 구하려 하는 경우 다음과 같은 Error 가 발생한다.
    SQL> create table TOY
    2 (Toy_ID NUMBER, Description LONG);
    Table created.
    SQL> select LENGTH(Description) from TOY;
    select LENGTH(Description) from TOY
    ERROR at line 1:
    ORA-00932: inconsistent datatypes
    "Inconsistent DataTypes" Error 는 LONG DataType 으로 정의된 Column 에
    Function 을 적용하였기 때문에 발생한다.
    VARCHAR2 Type 을 사용하면 정상 처리할 수 있으나, Oracle7 에서는 VARCHAR2 는
    2,000 Characters 만 저장할 수 있으며, Oracle8 에서는 4,000 Characters 이다.
    Oracle8 에서는 Long Data 를 저장하기 위해 LOB DataType 을 사용할 수 있으며,
    LONG Data Type 은 Oracle7/Oracle8 모두 Support 되므로 LONG Type 에 대해
    Length 를 확인하는 방법을 알아본다.
    Example
    다음은 anonymous PL/SQL Block 을 통해 TOY Table 에서 LONG Column 의
    Length 를 구하는 Script 이다.
    1. Single Record 에 대한 예
    $ vi len_long.sql
    declare
    length_var NUMBER;
    cursor TOY_CURSOR is
    select * from TO;
    toy_val TOY_CURSOR%ROWTYPE;
    begin
    open TOY_CURSOR;
    fetch TOY_CURSOR into toy_val;
    length_var := LENGTH(toy_val.Description);
    DBMS_OUTPUT.PUT_LINE('Length of Description: '||length_var);
    close TOY_CURSOR;
    end;
    SQL> set serveroutput on
    SQL> @len_long
    Length of description : 21
    PL/SQL procedure successfully completed.
    2. Multiple Record 에 대해서는 cursor FOR Loop 를 사용한다.
    $ vi len_long.sql
    declare
    length_var NUMBER;
    cursor TOY_CURSOR is
    select * from TOY;
    toy_val TOY_CURSOR%ROWTYPE;
    begin
    for toy_val in TOY_CURSOR loop
    length_var := LENGTH(toy_val.Description);
    DBMS_OUTPUT.PUT_LINE('ID: '||toy_val.Toy_ID);
    DBMS_OUTPUT.PUT_LINE('Length of Description: '||length_var);
    end loop;
    end;
    SQL> set serveroutput on
    SQL> @len_long
    ID: 1
    Length of Description: 21
    ID: 2
    Length of Description: 27
    PL/SQL procedure successfully completed.
    Reference Document
    ------------------

    Hi Frank,
    I have the exact same scenario where I have huge data coming from DB and its a must that I provide pagination.
    I tried implementing as per the document but the pagination is not working for me too.
    Details of the scenario:
    1. I have a session facade method which takes a searchCriteria (custom criteria) as the input parameter and returns a list of entities.
    a)This is the first method that I call as a default method activity in my taskflow.
    b)The result of this method is dragged and dropped as table in the jsff. (*which created a methodIterator in pageDef unlike the documentation which has accessorIterator*).
    2. I declared 2 class level variables
    a) List<Entity> result: which is set once the method in the (1) above is executed.
    b) long size: which is also set from the method (1) above.
    3. I defined getEntityAll(int index,int range) method which returns List<Entity> as per the index and range using the result (class level variable populated by method in 1)
    4. I defined getEntityAllSize() method which returns the size (class level variable populated by method in 1).
    5. I created the datacontrol on top of the session facade bean.
    6. I made sure to change the DataControlHandler = "oracle.adf.model.adapter.bean.DataFilterHandler"
    7. I've set the rangeSize = 25 in my pagedef.
    Now when I run my page, my default method activity calls the method in (1) above and populates the table, with a scroll bar.
    Once I start scrolling, it calls my method in (1) but it does not call either of the methods (getEntityAll(int index,int range) & getEntityAllSize()) which adds the pagination behavior.
    After this, my table has just 25 rows and further scrolling does not invoke any of the methods from the session bean.
    I'm using jdev : JDEVADF_11.1.1.4.0_GENERIC_101227.1736.5923 (11.1.1.4.0).
    Please let me know if I am missing anything.
    Thanks in advance!
    Swapna

  • Exception has occurred during data insertion ... Wrong number of parameters

    I am using an ADO dataflow source and an ADO dataflow destination to move data from a table on an IBM iSeries DB2 database to another IBM iSeries DB2 database on another machine.  The connection managers for source and destination both use .Net Providers\Odbc
    Data Provider with the Data Source Specification being ODBC connections specified on the Windows Server 2008 r2 machine hosting bids.  All the test connections work...so far so good.
    Issue is when I execute the control flow task the rows get picked up from the source DB2 database no problem but it fails on the insert to the destination DB2 table...The progress tab specifies the exceptions...
    [ADO NET Destination [601]] Error: An exception has occurred during data insertion, the message returned from the provider is: ERROR [07002] [IBM][System i Access ODBC Driver]Wrong number of parameters.
    [SSIS.Pipeline] Error: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "ADO NET Destination" (601) failed with error code 0xC020844B while processing input "ADO NET Destination Input" (604). The identified
    component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the
    failure.
    I put a data viewer on the data flow connection and the records I expect are  getting picked up and look ok. I checked to make sure the source and destination tables have the same number of columns in their record layout and identical data
    types and they look fine.
    Could someone kindly tell me whats going wrong?  Does the error message indicate that some of the columns are getting dropped from the dataset before the insert?
    Thanks much in advance for any help, Roscoe

    Hi Roscoe,
    Glad to hear that you have found the root cause. So, the issue occurs because numeric values with no decimal cannot be inserted into the Decimal data type column in the DB2 table. In SSIS, data type Decimal of DB2 database is mapped to data type DT_NUMERIC.
    To address the issue, you can do a data conversion for the column in question to define its precision and scale such as DT_NUMERIC(9,2) by using the Data Conversion Transformation before the ADO NET Destination.
    Regards,
    Mike Yin
    If you have any feedback on our support, please click
    here
    Mike Yin
    TechNet Community Support

  • Disabling data insertion in WFTASKHISTORY

    Hi
    In Orabpel.WFTaskPkg .. a procedure called 'updateTask' is defined;
    In the procedure following line is executed :
    IF p_IsVersionable = BOOLEAN_TRUE_STRING THEN
    createHistory(p_taskID);
    END IF;
    It inserts a record in the WFTASKHISTORY table if p_IsVersionable = true....
    Is it possible to set the value of 'p_IsVersionable' so that I can control the data insertion in WFTASKHISTORY table ? Any pointer will be helpful!!
    Thanks

    Hi Satish, this is an interesting question and as Michaela points out, Comments should be used to store non numeric data elements.
    However, your question makes me wonder what exectly do you want to enter characters for ? How would your use of characters for an amount be defined ? In case you would like to tell something about the amount (like the 100 for write-off is due to a customer not paying any bills), then you would use comments. I can imagine however that you want to use characters for sanother reason like adding new memebers to the database, but then you have to follow a different procedure.
    So please explain to what other use of characters you are thinking about.
    Best regards,
    Edwin van Geel

  • DECODE date bug

    Could someone else confirm this?
    We are using 9i R1.
    DECODE(<date field>, 'DD-MON-YYYY', , ) fails.
    ie.
         select decode (trunc(sysdate),'09-JUN-2003','Y','N') from dual ---> Returns 'N'
    But     select decode (trunc(sysdate),'09-JUN-03','Y','N') from dual ---> Returns 'Y'
    Thanks,
    Allan S.

    Can you give us an example of your tests, on my db it works in the where clause exactly the same as in the decode (and as expected).
    select EMPNO, HIREDATE from EMP
    where trunc(hiredate)='&1'
    Enter value for 1: 22.02.1981
           EMPNO HIREDATE
            7521 22.02.1981
    select EMPNO, HIREDATE from EMP
    where trunc(hiredate)='&1'
    Enter value for 1: 22.01.81
    no rows selected
    [pre]

  • Regarding ALV control: Tool tip for column data

    Hi Group,
    How can I give the tool tip for the data in ALV grid? For column headers I know that, but for the data in the colums how do I give the tool tip info.
    Regards,
    Kummi.

    Hello Kummi
    If you want to have a specific tooltip for an icon displayed in an ALV grid cell then you can use:
    @08<b>\Q</b> <tooltip text><b>@</b>  " shows own tooltip for icon @08@
    I am not sure if the same trick works for "normal" cell values. You may give it a try.
    Regards
      Uwe

  • Spatial data insert problem

    Hello,
    i want to make an spatial data insert, but it doesn't work well. Help would be fine.
    create table SCHIFFSPOSITION(
    SCHIFF_ID                    NUMBER NOT NULL,
    SCHIFF_NAME                VARCHAR(25),
    SYS_POS_SN               VARCHAR(25),
    SYS_LAT_P4_DER               VARCHAR(15),
    SYS_LON_P4_DER               VARCHAR(15),
    GEOM                          SDO_GEOMETRY,
    constraint PK_SCHIFFSPOSITION primary key(SCHIFF_ID));
    insert into MDSYS.USER_SDO_GEOM_METADATA values ('SCHIFFSPOSITION', 'GEOM',
    SDO_DIM_ARRAY (
    SDO_DIM_ELEMENT ('Longitude', -180, 180, .0005),
    SDO_DIM_ELEMENT ('Latitude', -90, 90, .0005)),8307);
    create index SCHIFFSPOS_IDX on SCHIFFSPOSITION(GEOM) indextype is MDSYS.SPATIAL_INDEX parameters('sdo_indx_dims=2, layer_gtype=point');
    INSERT INTO SCHIFFSPOSITION(SCHIFF_ID, SCHIFF_NAME, SYS_POS_SN, SYS_LAT_P4_DER, SYS_LON_P4_DER,
    MDSYS.SDO_GEOMETRY(2001,8307, MDSYS.SDO_POINT_TYPE(SYS_LON_GRAD_DER,SYS_LAT_GRAD_DER,null),null,null)))
    VALUES (1, 'METEOR 63', 'GPS', '33° 54,4246 S', '18° 25,9184 E', '18.4319736', '-33.9070772');
    thank you very much

    Hi,
    please insert that way:
    INSERT INTO SCHIFFSPOSITION(SCHIFF_ID, SCHIFF_NAME, SYS_POS_SN, SYS_LAT_P4_DER, SYS_LON_P4_DER,GEOM)
    VALUES (1, 'METEOR 63', 'GPS', '33° 54,4246 S', '18° 25,9184 E', MDSYS.SDO_GEOMETRY(
      2001
      ,8307
      , MDSYS.SDO_POINT_TYPE(
        18.4319736
        ,-33.9070772
        ,null
      ,null
      ,null
    )

  • How is the data inserted into JTF_RS_SALESREPS?

    Hi,
    I wanted to know how is the data inserted into JTF_RS_SALESREPS.When we import the resources from CRM Foundation responsibilty the data will be inserted into jtf_rs_resource_extns.I think we need to run a concurrent program to transfer data from jtf_rs_resource_extns to JTF_RS_SALESREPS.
    Which Concurrent program should be run?
    Please help.
    Thanks.

    How is the data inserted into CST_INV_QTY_TEMP table ?TABLE: BOM.CST_INV_QTY_TEMP
    http://etrm.oracle.com/pls/et1211d9/etrm_pnav.show_object?c_name=CST_INV_QTY_TEMP&c_owner=BOM&c_type=TABLE
    Thanks,
    Hussein

  • How is the data inserted into CST_INV_QTY_TEMP table?

    Hi All,
    How is the data inserted into CST_INV_QTY_TEMP table ?
    Thanks in advance,
    Mayur
    Edited by: 928178 on 17-Apr-2012 04:29

    How is the data inserted into CST_INV_QTY_TEMP table ?TABLE: BOM.CST_INV_QTY_TEMP
    http://etrm.oracle.com/pls/et1211d9/etrm_pnav.show_object?c_name=CST_INV_QTY_TEMP&c_owner=BOM&c_type=TABLE
    Thanks,
    Hussein

  • Strange data inserted into table via table trigger

    Hi ,
    There is some strange phenomenon happen occasionally where some tables update records will have a TRIGGER to insert records into a table and once in a while, the record has some strange data inserted which looks like a memory corruption. It is running on 10.2.0.3.
    Does anyone ever encounter this before?
    Strange result:
    PRIM_KEY
    -3.614364951000000000000000000000000E-47
    -3.614364951000000000000000000000000E-47
    Normal result:
    PRIM_KEY
    1137KT
    1137KT
    ana

    Hi,
    What is strange in this? Its not memory corruption. Its just one of the numeric form of representation of number
    -3.614364951000000000000000000000000E-47it means -3.614364951 * 10 to the power of -47.
    Whatever value has been entered into the table depends on your business logic you coded, and user input.
    Regards

Maybe you are looking for