カーソルを使用して一時テーブルを作成する簡単なソリューション。これには、すべての列を VARCHAR にするという制限があり、大量のデータの場合は遅くなります。
--** Set up example data
DECLARE @Source TABLE (ID INT, Name VARCHAR(50), [text] VARCHAR(200));
INSERT INTO @Source
(ID, Name, [text])
VALUES (1, 'SID,DOB', '123,12/01/1990')
, (2, 'City,State,Zip', 'NewYork,NewYork,01234')
, (3, 'SID,DOB', '456,12/21/1990');
--** Declare variables
DECLARE @Name VARCHAR(200) = '';
DECLARE @Text VARCHAR(1000) = '';
DECLARE @SQL VARCHAR(MAX);
--** Set up cursor for the tables
DECLARE cursor_table CURSOR FAST_FORWARD READ_ONLY FOR
SELECT s.Name
FROM @Source AS s
GROUP BY Name;
OPEN cursor_table
FETCH NEXT FROM cursor_table INTO @Name;
WHILE @@FETCH_STATUS = 0
BEGIN
--** Dynamically create a temp table with the specified columns
SET @SQL = 'CREATE TABLE ##Table (' + REPLACE(@Name, ',', ' VARCHAR(50),') + ' VARCHAR(50));';
EXEC(@SQL);
--** Set up cursor to insert the rows
DECLARE row_cursor CURSOR FAST_FORWARD READ_ONLY FOR
SELECT s.Text
FROM @Source AS s
WHERE Name = @Name;
OPEN row_cursor;
FETCH NEXT FROM row_cursor INTO @Text;
WHILE @@FETCH_STATUS = 0
BEGIN
--** Dynamically insert the row
SELECT @SQL = 'INSERT INTO ##Table VALUES (''' + REPLACE(@Text, ',', ''',''') + ''');';
EXEC(@SQL);
FETCH NEXT FROM row_cursor INTO @Text;
END
--** Display the table
SELECT *
FROM ##Table;
--** Housekeeping
CLOSE row_cursor;
DEALLOCATE row_cursor;
DROP TABLE ##Table;
FETCH NEXT FROM cursor_table INTO @Name;
END
CLOSE cursor_table;
DEALLOCATE cursor_table;