Thread: PL/pgsql declaration of string / bit / number with given (variable!) length

PL/pgsql declaration of string / bit / number with given (variable!) length

From
sneumann
Date:
Hi,

I have a PL/pgsql function that creates a certain bit string
based on the parameters. Things work fine if I use bit(10)
throughout the function. Now I'd like to return a bit string
with the given size "len", but that breaks with a syntax error:
       ret := B'0'::bit(len);LINE 1: SELECT  B'0'::bit( $1 )                           ^

Any suggestion how to return a (bit) string
of user-defined length ?

Thanks in advance,
Yours,
Steffen

CREATE OR REPLACE FUNCTION unarystr(   value integer,   len integer
) RETURNS bit(10) AS $$
DECLARE   ret bit(10);   one bit(10);
BEGIN   ret := B'0'::bit(10);   one := B'1'::bit(10);
   FOR num IN 0..value-1 LOOP      ret := ret | (one >>num);   END LOOP;   RETURN ret;
END;
$$ LANGUAGE plpgsql;


--
IPB Halle                    AG Massenspektrometrie & Bioinformatik
Dr. Steffen Neumann          http://www.IPB-Halle.DE
Weinberg 3                   http://msbi.bic-gh.de
06120 Halle                  New phone number !                            Tel. +49 (0) 345 5582 - 1470
               +49 (0) 345 5582 - 0 
sneumann(at)IPB-Halle.DE     Fax. +49 (0) 345 5582 - 1409


Re: PL/pgsql declaration of string / bit / number with given (variable!) length

From
Richard Huxton
Date:
sneumann wrote:
> Hi,
> 
> I have a PL/pgsql function that creates a certain bit string
> based on the parameters. Things work fine if I use bit(10)
> throughout the function. Now I'd like to return a bit string 
> with the given size "len", but that breaks with a syntax error:
> 
>         ret := B'0'::bit(len);
>     LINE 1: SELECT  B'0'::bit( $1 )
>                                ^
> 
> Any suggestion how to return a (bit) string 
> of user-defined length ?

Hmm - not sure it's possible (even theoretically) for a function to have 
multiple return types. Could you return a "bit varying" and cast it when 
received?

--   Richard Huxton  Archonet Ltd