我需要一个相当于 SQL Server 函数的 Postgres 函数convert
。我最终写了一个函数
CREATE OR REPLACE FUNCTION convert (target VARCHAR(50),source ANYELEMENT,style INT) RETURNS ANYELEMENT
AS
$$ BEGIN
CASE
when style=0 then CASE
WHEN target ='int' THEN return source::int;
WHEN target ='smallint' or target = 'tinyint' THEN return source::smallint;
WHEN target ='bigint' THEN return source::bigint;
WHEN target ='numeric' or target = 'real' or target = 'float' THEN return source::double precision;
WHEN target ='smallmoney' or target = 'money' or target = 'decimal' THEN return source::double precision;
WHEN target ='char' THEN return source::char;
WHEN target ='datetime' or target = 'smalldatetime' then return source::timestamp;
WHEN target like 'varchar%' or target like 'nvarchar%' THEN return source::varchar;
WHEN target = 'text' or target like 'ntext' THEN return source::text;
WHEN target = 'timestamp' THEN return source::varchar(30);
WHEN target = 'binary' or target='varbinary' THEN return source::bytea;
WHEN target = 'uniqueidentifier' THEN return source::varchar(37);
WHEN target = 'sysname' THEN return source::varchar(128);
WHEN target = 'sql_variant' THEN return varchar;
WHEN target = 'bit' THEN if source::varchar='1' THEN return true; ELSIF source::varchar='0' THEN return false; else RAISE EXCEPTION 'Invalid value for Input boolean'; END IF;
ELSE return source::anyelement;
END CASE;
when style!=0 then CASE
WHEN (style = 0 OR style = 100) THEN return to_timestamp(source::text,'mon dd yyyy hh:miAM');
WHEN style = 1 THEN return to_timestamp(source::text,'mm/dd/yy');
WHEN style = 101 THEN return to_timestamp(source::text,'mm/dd/yyyy');
..
..
END CASE;
END CASE;
END;
$$ LANGUAGE plpgsql;
在调用函数 asselect convert('int','1',0)
时,它会引发以下错误:
“错误:无法确定多态类型,因为输入类型为“未知”1 语句失败。”
当我将第二个参数显式转换为 convert('int','1'::text,0) 时,它可以工作。但我需要打电话而不做任何额外的演员。有人可以帮忙吗?