Thursday, October 18, 2012

Insert Rows into Columns in SQL Server



DECLARE @i INT,@SQL VARCHAR(1000),@ColVal varchar(1000);
DECLARE RowDataToColumn CURSOR FOR

SELECT Testing FROM Test1
FOR READ ONLY

OPEN RowDataToColumn
FETCH NEXT FROM RowDataToColumn INTO @colval

SELECT @SQL = 'INSERT INTO Test2 VALUES(',
@i = 0

WHILE @@FETCH_STATUS = 0
BEGIN
if @i = 0 -- First append
SET @SQL = @SQL + '''' + @colval + ''''
else
SET @SQL = @SQL + ', ''' + @colval + ''''

FETCH NEXT FROM RowDataToColumn INTO @colval
SET @i = @i + 1
END
CLOSE RowDataToColumn
DEALLOCATE RowDataToColumn

SET @SQL = @SQL + ')'

EXEC(@SQL) -- This executes insert

No comments: