Select 来自 DB 的更多值到 DataSet 中的一个字段

Select more values from DB into one field in DataSet

我需要 select 来自数据库的更多值并将其放入数据集中的一个字段中。

我在 delphi 中有方法,它有输入参数 TDataSet 并将值从数据集导出到 Excel。

我要导出的字段之一是多个值,这些值与其他 table 用“,”分隔。

我有这个 tables:

目录

ID_Katalog | atribut_1
----------------------
1          | xxx

KATALOGxPOLOZKA

ID_POLOZKA | ID_KATALOG
-----------------------
1          | 1
2          | 1
3          | 1

我需要这个结果:

ID_Katalog | atribut_1 | polozka
--------------------------------
1          | xxx       | 1, 2, 3

请问有什么办法吗?

我试过子查询,但子查询无法return超过 1 个值。

P.S。 : 我正在使用 - Delphi XE6、ADODB、MS SQL-SERVER.... 结果必须是 TDataSet

您可以在子选择中使用 FOR XML 子句来连接,如下所示:

SELECT
      K.ID_Katalog,
      K.attribut_1,
      STUFF
      (
         (
            SELECT
                  ', ' + CAST(P.ID_POLOZKA AS varchar)
               FROM
                  KATALOGxPOLOZKA P
               WHERE
                  P.ID_KATALOG = K.ID_Katalog
               FOR XML PATH('')
         ), 1, 2, ''
      ) AS polozka
   FROM
      KATALOG K;

像:

recs:=sqlExecute(join the tables)
while not recs.eof() do
begin
  s:=recs.fields['join field from master table')
  dataset.append, and init other fields
  while (not recs.eof()) and s=recs.fields['join field from master table') do
  begin
    dataset.fields['concat field']:=dataset.fields['concat field'] + recs.field['polozka'] + ', ';
    recs.next;
  end;
  cut trailing comma
  dataset.post;  
end;