CREATE FUNCTION dbo.GenericStringAgg ( @tableName NVARCHAR(MAX), @columnName NVARCHAR(MAX), @groupColumn NVARCHAR(MAX), @groupValue NVARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @sql NVARCHAR(MAX); DECLARE @result NVARCHAR(MAX); SET @sql = N'SELECT @result = STUFF(( SELECT '','' + ' + @columnName + ' FROM ' + @tableName + ' WHERE ' + @groupColumn + ' = ''' + @groupValue + ''' FOR XML PATH(''''), TYPE ).value(''.'', ''NVARCHAR(MAX)''), 1, 2, '''')'; EXEC sp_executesql @sql, N'@result NVARCHAR(MAX) OUTPUT', @result OUTPUT; RETURN @result; END