Task at hand is to aggregate the values into comma-separated string using SqlAlchemy with SQL Server 2017:
So I use string_agg()
to do so:
query = session.query(Table.key, func.string_agg(Table.value, ',')).group_by(Table.key).all()
But the query always returns an error:
Argument data type nvarchar is invalid for argument 2 of string_agg function
sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Argument data type nvarchar is invalid for argument 2 of string_agg function. (8116) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)')
I tried a number of methods to avoid this error (e.g. cast the constant parameter "," to string, or using sub_query() to add the separator as a constant column) but still no luck.
So, what is the proper way to invoke string_agg()
in SqlAlchemy?