2013-04-01 5 views
0

Oracle 11G를 사용하고 있으며 날짜를 수동으로 데이터베이스에 입력하고 불행히도 여러 번 잘못된 날짜를 입력하는 날짜 열 (Var char 2)이 있습니다. 일종의 REGEXP LIKE 문을 사용하여 유효한 날짜 필드 만 선택하고 싶습니다. 가능한 선택 가능한 형식은 다음과 같습니다.REGEXP를 사용하여 날짜 필드의 유효성을 검사하는 Oracle

DATE 

JULY 31, 2009 
7/31/2009 
31-JUL-09 

내가 원하지 않는이 세 가지 형식은 아닙니다. 누군가가이 유효한 날짜 형식을 선택하기 위해 REGEXP 또는 다른 방법을 찾도록 도와 줄 수 있습니까? 미리 감사드립니다.

+2

아주 좋은 날짜는 ** 날짜로 저장해야하는 이유 이유 **이 아닌 텍스트로. –

+0

'REGEXP_LIKE' 문을 쓸 것을 요청하고 있습니까? 이것은 정말로 문제가되지 않습니다. 그것은 당신이 스스로 알아낼 수있는 것입니다, 그렇죠? 이미 REGEXP_LIKE를 사용해야한다는 것을 이미 알고 있으므로 게으르지 마시고 글을 쓰지 마세요. – Scotch

+0

Scotch 하나의 REGEXP_LIKE에서 세 가지 형식의 REGEXP를 작성하는 방법을 알고 있다면 스스로 처리 하겠지만 작동시키지 못합니다. 도움이되는 입력 주셔서 감사합니다 ... – swingard

답변

1

정규식 대신 PL/SQL을 사용해보십시오. 상당히 느리지 만 유지 관리 및 확장이 더 안전하고 쉽습니다. 올바르게 수행하려면 Oracle 형식 모델을 사용해야합니다. 정규 표현식을 사용하여이 정보의 유효성을 검증하려는 많은 시도를 보았습니다. 그러나 거의 제대로 수행되지 않았습니다.

실제 성능에 대해 신경 쓰는 분은 데이터 모델을 수정하는 것이 가장 좋습니다.

코드 및 테스트 케이스 :

--Function to convert a string to a date, or return null if the format is wrong. 
create or replace function validate_date(p_string in string) return date is 
begin 
    return to_date(p_string, 'MONTH DD, YYYY'); 
exception when others then 
    begin 
     return to_date(p_string, 'MM/DD/YYYY'); 
    exception when others then 
     begin 
      return to_date(p_string, 'DD-MON-RR'); 
     exception when others then 
      return null; 
     end; 
    end; 
end; 
/

--Test individual values 
select validate_date('JULY 31, 2009') from dual; 
2009-07-31 
select validate_date('7/31/2009') from dual; 
2009-07-31 
select validate_date('31-JUL-09') from dual; 
2009-07-31 
select validate_date('2009-07-31') from dual; 
<null> 

간단한 성능 테스트 :

--Create table to hold test data 
create table test1(a_date varchar2(1000)) nologging; 

--Insert 10 million rows 
begin 
    for i in 1 .. 100 loop 
     insert /*+ append */ into test1 
     select to_char(sysdate+level, 'MM/DD/YYYY') from dual connect by level <= 100000; 

     commit; 
    end loop; 
end; 
/

--"Warm up" the database, run this a few times, see how long a count takes. 
--Best case time to count: 2.3 seconds 
select count(*) from test1; 


--How long does it take to convert all those strings? 
--6 minutes... ouch 
select count(*) 
from test1 
where validate_date(a_date) is not null; 
관련 문제