Question

my goal is to write a stored proc that can collect all field values from multiple rows into one single output variable (maybe varchar(some_length)). It may seem strange solution but i've quite positive its the only one i can use at that situation im in. I have not used Firebird before and stored procs look way different than in other well-known db systems. My Firebird is 1.5 and dialect 3 (not sure what it means). So maybe someone could help me with a algorithm example.

Was it helpful?

Solution

The following procedure does what you describe:

SET TERM !!;
CREATE PROCEDURE concat_names
  RETURNS (concat VARCHAR(2000))
AS
DECLARE VARIABLE name VARCHAR(100);
BEGIN
  concat = '';
  FOR SELECT first_name || ' ' || last_name FROM employee INTO :name
  DO BEGIN
    concat = concat || name || ', ';
  END
END!!
SET TERM ;!!
EXECUTE PROCEDURE concat_names;

But I question the wisdom of this solution. How do you know the VARCHAR is long enough for all the rows in your desired dataset?

It's far easier and safer to run a query to return the result to an application row by row. Every application programming language has methods to concatenate strings, but more importantly they have more flexible methods to manage the growth of data.

By the way, "dialect" in Firebird and InterBase refers to a compatibility mode that was introduced so that applications developed for InterBase 5.x can work with later versions of InterBase and Firebird. That was almost ten years ago, and AFAIK there's no need today to use anything lower than dialect 3.

OTHER TIPS

You have to test for null values when concatenating, here is an example for two fields and a separator between them:

    CREATE PROCEDURE CONCAT(
    F1 VARCHAR(385),
    F2 VARCHAR(385),
    SEPARATOR VARCHAR(10))
RETURNS (
    RESULT VARCHAR(780))
AS
begin

  if ((:f1 is not null) and (:f1 <> '')) then
    result = :f1;

  if ((:f2 is not null) and (:f2 <> '')) then
    if ((result is not null) and (result <> '')) then
      begin
        if ((:separator is not null) and (separator <> '')) then
          result = result||separator||f2;
        else
          result = result||f2;
      end
    else
      result = f2;

  suspend;
end

Returning multiple rows using Firebird stored procedures is very very easy.

Don't use:

execute procedure proc_name(value);

Instead use the:

select * from proc_name(value);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top