Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在类型转换过程中发生异常时,将条目添加到另一个表中。Postgres(PL/pgSQL)_Sql_Postgresql_Plpgsql - Fatal编程技术网

在类型转换过程中发生异常时,将条目添加到另一个表中。Postgres(PL/pgSQL)

在类型转换过程中发生异常时,将条目添加到另一个表中。Postgres(PL/pgSQL),sql,postgresql,plpgsql,Sql,Postgresql,Plpgsql,对于名为some_table的源表,其结构和数据如下: rownumber (numeric) | some_column (text) ------------------------------------------ 41 | 12/03/2016 42 | invalid-text-here 43 | 24/04/2016 以下函数用于将包含日期值的文本转换为时间戳,当

对于名为
some_table
的源表,其结构和数据如下:

rownumber (numeric)  |  some_column (text)
------------------------------------------
 41                  |  12/03/2016
 42                  |  invalid-text-here
 43                  |  24/04/2016
以下函数用于将包含日期值的文本转换为时间戳,当转换失败时,它返回一个
null

CREATE FUNCTION convert_to_date (scolumn anyelement, format text) RETURNS timestamp AS $$
    BEGIN
        BEGIN
            RETURN cast(to_timestamp(scolumn, format) as timestamp  without time zone);
        exception when others then
            RETURN null;
        END;
    END;
$$ LANGUAGE plpgsql;
它是这样使用的-

SELECT convert_to_date(some_column, 'DD/MM/YYYY') from some_table;
这很有效。 但我现在想保留一个记录,记录转换失败的所有值(上表中的无效文本)到另一个表中,即:每当发生异常时。因此,在异常块中,它应该执行如下操作:

exception when others then
    INSERT INTO another_table(column_name, row_number, errval) VALUES (scolumn, rownumber, errval)
    RETURN null;
END;

如何获取
行号
errval


例如,对于第二行,
rownumber
应该是42
errval
应该是“invalid-text-here”,您可以更新函数,如下所示:

CREATE FUNCTION convert_to_date (scolumn anyelement,rownumber numeric, format text) RETURNS timestamp AS $$
    BEGIN
        BEGIN
            RETURN cast(to_timestamp(scolumn, format) as timestamp  without time zone);
        exception when others then
INSERT INTO another_table(column_name, row_number, errval) VALUES (scolumn, rownumber, 'invalid-text-here')
            RETURN null;
        END;
    END;
$$ LANGUAGE plpgsql;
打电话就像

SELECT convert_to_date(some_column,row_number, 'DD/MM/YYYY') from some_table;

希望它能有所帮助。

您可以更新您的函数,如下所示:

CREATE FUNCTION convert_to_date (scolumn anyelement,rownumber numeric, format text) RETURNS timestamp AS $$
    BEGIN
        BEGIN
            RETURN cast(to_timestamp(scolumn, format) as timestamp  without time zone);
        exception when others then
INSERT INTO another_table(column_name, row_number, errval) VALUES (scolumn, rownumber, 'invalid-text-here')
            RETURN null;
        END;
    END;
$$ LANGUAGE plpgsql;
打电话就像

SELECT convert_to_date(some_column,row_number, 'DD/MM/YYYY') from some_table;
希望能有帮助