0

Is is okay to use a variable to concatenate a value from several rows ( as an implicit aggregate function )? It seems to work fine on my machine, but I haven't seen it recommended.

declare @v_str varchar(4000) = ''
select top 5 @v_str = @v_str + ',' + city_name from city_table order by city_name
print @v_str
monkeyhouse
  • 2,875
  • 3
  • 27
  • 42
  • Assuming you're using SQL Server the generally accepted method based documented features uses XML and `Stuff()` to assemble the string. If you have a look at the "Related" links for this question (over on the right side of the page) you should find some examples. Tip: It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. `sql-server-2014`. Differences in syntax and features often affect the answers. `tsql` narrows the choices, but does not specify the database. – HABO May 28 '17 at 03:43
  • 1
    On thing that you should be aware of: **[nvarchar concatenation / index / nvarchar(max) inexplicable behavior](https://stackoverflow.com/questions/15138593/nvarchar-concatenation-index-nvarcharmax-inexplicable-behavior)** – Lukasz Szozda Jun 04 '17 at 16:19

1 Answers1

0

From nvarchar concatenation / index / nvarchar(max) inexplicable behavior "The correct behavior for an aggregate concatenation query is undefined."

monkeyhouse
  • 2,875
  • 3
  • 27
  • 42