Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Oddity with String_Agg

Tags:

sql-server

This query returns the wrong results for the second string Agg function:

select
string_agg(t.name, ';') as BBB,
string_agg(t.name, ', ' ) as CCC
from sys.tables as t 

But it works if you alter t.name eg:

select
string_agg(t.name, ';') as BBB,
string_agg('' + t.name, ', ' ) as CCC
from sys.tables as t 

Any idea why? Is this a bug?

like image 514
Peppermallow Avatar asked Sep 19 '25 13:09

Peppermallow


1 Answers

Interesting, it is a bug, sure. It checks the first argument and use it as a cache for the second.

It runs odd on sys.* objects

But the query runs successfully on other database tables.

I executed the exact query with execution plan.

enter image description here

And what is more interesting, when I executed the query on a user database on a different table, the query returns expected data.

There is no error in this case

enter image description here

like image 163
Eralper Avatar answered Sep 21 '25 09:09

Eralper