1

文字列を日付に変換する関数を提案できる人はいますか?

> This Function will takes a string and give:
> 0000-00-00 if string cannot be converted (string in <> date out) 
> NULL if String NULL or blank(string in = date out) 
> yyyy-mm-dd if string can be converted (string in = date out)
4

1 に答える 1

1
> This Function will takes a string and give:
> 0000-00-00 if string cannot be converted (string in <> date out) 
> NULL if String NULL or blank(string in = date out) 
> yyyy-mm-dd if string can be converted (string in = date out)

Drop function if exists stringtodate;

DELIMITER $$

CREATE FUNCTION `stringtodate`(v TEXT) Returns DATE 
BEGIN
DECLARE result DATE;

IF (v Is Null or v = '') THEN SET result = NULL;
ELSEIF (STR_TO_DATE(v,'%d-%m-%Y') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%d-%m-%Y');
ELSEIF (STR_TO_DATE(v,'%d,%m,%Y') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%d,%m,%Y');
ELSEIF (STR_TO_DATE(v,'%d/%m/%Y') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%d/%m/%Y');
ELSEIF (STR_TO_DATE(v,'%Y-%m-%d') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%Y-%m-%d');
ELSEIF (STR_TO_DATE(v,'%Y,%m,%d') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%Y,%m,%d');
ELSEIF (STR_TO_DATE(v,'%Y/%m/%d') IS NOT NULL AND length(clean(v)) > 8) THEN SET result = STR_TO_DATE(v,'%Y/%m/%d');
ELSEIF (STR_TO_DATE(v,'%d-%m-%y') IS NOT NULL AND length(clean(v)) < 10) THEN SET result = STR_TO_DATE(v,'%d-%m-%y');
ELSEIF (STR_TO_DATE(v,'%d,%m,%y') IS NOT NULL AND length(clean(v)) < 10) THEN SET result = STR_TO_DATE(v,'%d,%m,%y');
ELSEIF (STR_TO_DATE(v,'%d/%m/%y') IS NOT NULL AND length(clean(v)) < 10) THEN SET result = STR_TO_DATE(v,'%d/%m/%y');

ELSE SET result = CAST("0000-00-00" AS DATE);

END IF;

Return result;

END
于 2013-05-02T10:35:35.317 に答える