title: Postgresql equivalent for SQL Server function Convert
body: <p>I am in need of a Postgres function which is equivalent to SQL Server function <code>convert</code>. I ended up writing a function</p>
  
  <pre><code>    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;
  </code></pre>
  
  <p>While calling the function as <code>select convert('int','1',0)</code>, it throws the following error:</p>
  
  <blockquote>
    <p>"ERROR: could not determine polymorphic type because input has type "unknown" 1 statement failed."</p>
  </blockquote>
  
  <p>When I do an explicit cast of second parameter as convert('int','1'::text,0), it works. But I need to call without doing any additional cast. Can someone help?</p>