我有一个包含TO_DATE(expiry_date, 'YYMM')
表达式的选择查询。
如果expiry_date
为YYMM
格式,则有效。
如果0001
的格式不正确,我希望将数据设置为expiry_date
YYM
,YY
,MM
,YMM
等。< / p>
这可能吗?
答案 0 :(得分:2)
SELECT CASE
WHEN LENGTH(expiry_date) = 4
THEN TO_DATE(expiry_date, 'YYMM')
ELSE TO_DATE('0001', 'YYMM')
END AS d_date
FROM
(
SELECT 1212 expiry_date FROM DUAL UNION ALL
SELECT 1211 FROM DUAL UNION ALL
SELECT 1210 FROM DUAL UNION ALL
SELECT 121 FROM DUAL UNION ALL
SELECT 12 FROM DUAL
)
;
/*
2012-12-01 00:00:00
2012-11-01 00:00:00
2012-10-01 00:00:00
2000-01-01 00:00:00
2000-01-01 00:00:00
*/
这样的东西?
答案 1 :(得分:2)
嗯,这很难看,但似乎可以解决问题:
WITH data AS (
SELECT '123' AS val FROM dual
UNION SELECT '12' FROM dual
UNION SELECT '1' FROM dual
UNION SELECT '12345' FROM dual
UNION SELECT '9612' FROM dual -- ok
UNION SELECT '9613' FROM dual -- wrong
UNION SELECT '1296' FROM dual -- wrong
UNION SELECT 'AAAA' FROM dual -- wrong
)
SELECT
CASE
WHEN length(val) != 4
OR NOT regexp_like(val, '[0-9]{4}')
OR NOT to_number(substr(val, 3, 2)) BETWEEN 1 AND 12
THEN to_date('0010', 'YYMM')
ELSE to_date(val, 'YYMM')
END AS date_yymm
FROM data;
输出:
DATE_YYMM ---------- 01-10-2000 01-10-2000 01-10-2000 01-10-2000 01-10-2000 01-12-2096 01-10-2000 01-10-2000
或者你可以使用一个函数:
CREATE OR REPLACE FUNCTION is_date_format(p_value IN VARCHAR2, p_format IN VARCHAR2) RETURN NUMBER
AS
l_dummy DATE;
BEGIN
l_dummy := to_date(p_value, p_format);
RETURN 0;
EXCEPTION
WHEN OTHERS THEN
RETURN 1;
END;
/
WITH data AS (
SELECT '123' AS val FROM dual
UNION SELECT '12' FROM dual
UNION SELECT '1' FROM dual
UNION SELECT '12345' FROM dual
UNION SELECT '9612' FROM dual -- ok
UNION SELECT '9613' FROM dual -- wrong
UNION SELECT '1296' FROM dual -- wrong
)
SELECT
-- fx for exact matching as pointed out by Nicholas Krasnov
DECODE(is_date_format(val, 'fxYYMM'), 0, val, '0010')
FROM data;