I\'m trying to make a stored procedure that will create a temporary table A whose columns would be dependent on the number of rows of another table, B. The background for th
You should not do this - instead, make the group name a column in table A as well.
DECLARE @sSQL varchar(max),
@ColumnName CHAR(128)
DECLARE TableCursor CURSOR FOR
SELECT ColumnName FROM GroupTable
SET @sSQL = 'CREATE TABLE ##NewTempTable ('
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sSQL = @sSQL + RTRIM(@ColumnName) + ' CHAR(10) ,'
FETCH NEXT FROM TableCursor INTO @ColumnName
END
CLOSE TableCursor
DEALLOCATE TableCursor
SET @sSQL = @sSQL + ')'
EXEC (@sSQL)
SELECT * FROM ##NewTempTable
I hope this helps. In the DECLARE CURSOR, you will need to change the "ColumnName" and "TableName" to your actual column/table that you are querying.