I can't think of a plausible scenario where this transform serves any useful purpose because relational-algebra is, by design, about sets of data sharing the same attributes (i.e. tables have rows with columns) - by having everything in a single row with meaningless columns you're just effectively serializing data into a blob.
The only way to achieve this is using Dynamic SQL, as this is the only way to achieve a dynamic number of columns without prior knowledge of what columns are desired.
In MS SQL Server you might think of using PIVOT/UNPIVOT but the columns still need to be manually named, thus requiring Dynamic SQL.
MySQL Server (and MariaDB) have GROUP_CONCAT
which can be used to combine multiple rows into a single string (text) value but the server lacks any kind of "split" function. So GROUP_CONCAT
doesn't work here because it doesn't return discrete columns.
In T-SQL (MS SQL Server, Sybase) you need to iterate over every target row, this is done using a CURSOR
. You cannot reliably perform string concatenation inside a SELECT
statment:
DECLARE @sql nvarchar(max) = 'SELECT '
DECLARE c CURSOR FOR
SELECT [Id], [Name] FROM Students ORDER BY [Id] ASC
OPEN c
DECLARE @id int
DECLARE @name nvarchar(100)
FETCH NEXT FROM c INTO @id, @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = @sql + CONVERT( varchar(10), @id ) + ', ' + @name
FETCH NEXT FROM c INTO @id, @name
END
CLOSE c
DEALLOCATE c
sp_executesql @sql -- this will execute the `SELECT` that was generated, where each discrete value will be returned as an anonymous column.