creating dynamic columns in a stored procedure

  • Hi,

    What I want to know is how do I create dynamic columns for a temp table in a stored procedure;?

    Here is the start of the procedure..

    CREATE PROCEDURE Sp_GetAvergaeSales

    (

    @StartDate Datetime,

    @EndDate DateTime,

    @NumOfWeeks int

    )

    AS

    Declare

    @i int,

    @ColumnName varchar(10)

    create table #weeks(XSeries varchar(12), Turnover money)

    set @i = 0

    while @i <= @NumOfWeeks

    begin

    set @ColumnName = 'Turnover' + cast(@i as varchar(2))

    --alter table #weeks Add @ColumnName money -- This doesnt work.... 🙂

    set @i = @i + 1

    end

    Q) How do I add the dynamic number of columns in this procedure, Any ideas...

  • Try this,

    CREATE PROCEDURE Sp_GetAvergaeSales

    (

    @StartDate Datetime,

    @EndDate DateTime,

    @NumOfWeeks int

    )

    AS

    Declare

    @i int,

    @ColumnName varchar(10),

    @AlterTable varchar(100),

    @AddColumn varchar(100),

    @tsqlalter varchar(100)

    create table #weeks(XSeries varchar(12), Turnover money)

    set @i = 0

    while @i <= @NumOfWeeks

    begin

    set @ColumnName = 'Turnover' + cast(@i as varchar(2))

    select @alterTable='alter table #weeks'

    select @Addcolumn = @columnname

    SELECT @tsqlalter = @AlterTable+@AddColumn+'money'

    --alter table #weeks Add @ColumnName money -- This doesnt work.... 🙂

    set @i = @i + 1

    end

  • Opps I am sorry u have to add this in the code too

    EXEC(@tsqlalter)

    --after the

    SELECT @tsqlalter = @AlterTable+@AddColumn+'money'

    so it should be

    SELECT @tsqlalter = @AlterTable+@AddColumn+'money'

    EXEC(@tsqlalter)

  • In addition to the "EXEC" always have TRY..CATCH block to avoid any un-expected errors during the operations.

  • Mayank's code is missing one more thing, and that is the word "ADD" in front of the column name... but you can easily correct that.

  • thanks 🙂

  • nice

  • Thanks its works fine

Viewing 8 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic. Login to reply