Procedure to create a table with a variable number of columns

前端 未结 2 962
说谎
说谎 2020-12-22 11:54

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

相关标签:
2条回答
  • 2020-12-22 12:00

    You should not do this - instead, make the group name a column in table A as well.

    0 讨论(0)
  • 2020-12-22 12:05
    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.

    0 讨论(0)
提交回复
热议问题