问题
I have below SELECT query in a procedure. I need to add another validation check for SUBMTD_SRVC_DATE column. If the value of SUBMTD_SRVC_DATE is in any format other than 'MMDDYYYY', then I need to populate '00000000'. Suppose, if SUBMTD_SRVC_DATE = '100515', then I need to automatically populate '00000000'.
Could anyone please on that. Thanks in advance.
SELECT CASE WHEN SMS.SRVC_UNITS IS NULL OR SMS.SRVC_UNITS = -8888 OR SMS.SRVC_UNITS = -9999 THEN '0000000' ELSE LPAD( SMS.SRVC_UNITS , 7 , '0') END
|| CASE WHEN ( SMS.SUBMTD_SRVC_DATE IS NULL OR UPPER(SMS.SUBMTD_SRVC_DATE) = 'NOT AVAILABLE') THEN '00000000' ELSE SMS.SUBMTD_SRVC_DATE END AS FILE_VAL
FROM SUBMTD_MED_SRVC SMS
回答1:
Create a user-defined function and try to parse the date; if there are any exceptions then capture them and return your default string.
CREATE FUNCTION check_Date (
datestring VARCHAR2,
format_mask VARCHAR2 := 'FXMMDDYYYY',
default_value VARCHAR2 := '00000000'
) RETURN VARCHAR2 DETERMINISTIC
IS
INVALID_DATE EXCEPTION;
PRAGMA EXCEPTION_INIT( INVALID_DATE, -20001 );
p_date DATE;
BEGIN
IF datestring IS NULL THEN
RAISE INVALID_DATE;
END IF;
p_date := TO_DATE( datestring, format_mask );
RETURN datestring;
EXCEPTION
WHEN OTHERS THEN
RETURN default_value;
END check_Date;
/
Alternative:
SELECT CASE
WHEN NOT REGEXP_LIKE( datestring, '^(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{4}$' )
THEN '00000000'
WHEN TO_CHAR(
ADD_MONTHS(
TRUNC( TO_DATE( SUBSTR( datestring, 5 ), 'YYYY' ), 'YYYY' ),
TO_NUMBER( SUBSTR( datestring, 1, 2 ) ) - 1
)
+ TO_NUMBER( SUBSTR( datestring, 3, 2 ) ) - 1,
'MMDDYYYY'
)
<> datestring
THEN '00000000'
ELSE datestring
END
FROM your_table
回答2:
One option might be to create a function that attempts to use TO_DATE to cast the input you're receiving into a a real DATE. If it succeeds, you know your date is valid, and return the original string, if it fails and throws an exception, you catch the exception and return '000000':
create or replace function validate_date_string (
p_date_string varchar2
)
return varchar2
is
l_date date;
l_date_string varchar2(8);
begin
l_date_string := p_date_string;
begin
l_date := to_date (p_date_string, 'MMDDYYYY');
exception
when others then l_date_string := '000000';
end;
return l_date_string;
end;
/
来源:https://stackoverflow.com/questions/44018443/check-date-format-in-oracle