2017-08-03 178 views
1

我有一個帶有5個記錄的字段sourcefilename的表。以下是記錄。檢查字符串是否有效

SN. SOURCEFILENAME 
1. 20170215095453_1.Iredell Memorial Hospital Dental Eligibility.xls_INFREPT01.txt 
2. Iredell Memorial Hospital Eligibility April 2017.xls_INFREPT01.txt 
3. Iredell Memorial Hospital Eligibility March 2017.xls_INFREPT01.txt 
4. Iredell Memorial Hospital Eligibility May 2017.xls_INFREPT01.txt 
5. Iredell Memorial Hospital October 2016 Dental Eligibility.xls_EligData.txt 

我只需要提取前8個字符,並檢查它是否有效的日期。如果是有效日期,則返回TRUE else FALSE。

我試過了ISDATE函數。還有其他的選擇嗎?

SELECT DISTINCT SubStr(sourcefilename,1,8), 
CASE WHEN isdate(SubStr(sourcefilename,1,8),'YYYYMMDD') = 1 THEN 'TRUE' ELSE 'FALSE' END FROM ai_4451_1_metl; 
+0

@ user7294900:如果使用TO_DATE。比較什麼價值? SELECT DISTINCT SubStr(sourcefilename,1,8), CASE WHEN to_Date(SubStr(sourcefilename,1,8),'YYYYMMDD')= ???????? THEN'TRUE' ELSE'FALSE'END FROM ai_4451_1_metl; –

回答

3

沒有甲骨文BUILT_IN isdate()或命名不同當量(在版本12cR2之前)。但是你可以寫你自己:

create or replace function isdate 
    (p_date_str in varchar2 
    , p_date_fmt in varchar2) 
    return varchar2 
is 
    return_value varchar2(5); 
    l_date date; 
begin 
    begin 
     l_date := to_date(p_date_str, p_date_fmt); 
     return_value := 'TRUE'; 
    exception 
     when others then 
      return_value := 'FALSE'; 
    end; 
    return return_value; 
end; 
/

如果鑄造的字符串與DATE數據類型成功這是一個有效的日期,否則就不是。

4

Oracle 12.2提供了一個新功能VALIDATE_CONVERSION。到目前爲止,我從來沒有使用過,但我相信它會是這樣:

CASE VALIDATE_CONVERSION(SubStr(sourcefilename,1,8) AS DATE, 'YYYYMMDD') 
    WHEN 1 THEN 'TRUE' 
    ELSE 'FALSE' 
END 
3

如果你有甲骨文12.2您可以使用validate_conversion功能:

with demo as 
    (select '20170101' as sourcetest from dual union all 
     select '20171100' from dual) 
select sourcetest 
    , validate_conversion(sourcetest as date, 'YYYYMMDD') as test_result 
from demo; 

SOURCETEST TEST_RESULT 
----------- ----------- 
20170101    1 
20171100    0 
相關問題