Firebird 2.1 stored procedure for combining text in multiple lines

I am trying to write a stored procedure to combine several lines of text together to return it as one line. For instance:

CREATE TABLE TEST (
 ID INTEGER,
 SEQ INTEGER,
 TEXT VARCHAR(255));

COMMIT;

INSERT INTO TEST (ID, SEQ, TEXT) VALUES (1, 1, "LINE 1");
INSERT INTO TEST (ID, SEQ, TEXT) VALUES (1, 2, "LINE 2");
INSERT INTO TEST (ID, SEQ, TEXT) VALUES (1, 3, "LINE 3");

COMMIT;

SET TERM !!;
CREATE PROCEDURE concat_names (iID INTEGER)
  RETURNS (CONCAT VARCHAR(2000))
AS
DECLARE VARIABLE name VARCHAR(255);
BEGIN
  CONCAT = '';
  FOR SELECT TEXT FROM TEST where id=:iID INTO :name
  DO BEGIN
    CONCAT = CONCAT || name;
  END
END!!
SET TERM ;!!

commit;

However, when I run:

select concat from concat_names(1);

It always returns null rows.

Any ideas?

+3
source share
3 answers

You forgot about SUSPEND. Your proc should look like this:

SET TERM !!;
CREATE PROCEDURE concat_names (iID INTEGER)
  RETURNS (CONCAT VARCHAR(2000))
AS
DECLARE VARIABLE name VARCHAR(255);
BEGIN
  CONCAT = '';
  FOR SELECT TEXT FROM TEST where id=:iID INTO :name
  DO BEGIN
    CONCAT = CONCAT || name;
  END
  SUSPEND;
END!!
SET TERM ;!!

You can achieve the same result without saving proc. Use the LIST aggregation function:

SELECT LIST(text, '') FROM TEST where id=:iID 

The second parameter LIST is a delimiter. If you call LIST with only the field name, then the comma ',' will be used to separate the values.

+7

, TEST null, , :

 CONCAT = CONCAT || coalesce(name,'');

CONCAT = CONCAT || name;
0

Without using the stored version of Proc and using Firebird 2.5, the LIST aggregation function returns “Concatenating non-NULL comma-delimited rows in a column” *. Using the above TEST table, SQL

SELECT LIST(TEXT)
    FROM TEST

returns

LINE 1, LINE 2, LINE 3

This may be of some interest.

* Discontinued from the Firebird man page here

0
source

Source: https://habr.com/ru/post/1776928/


All Articles