Results 1 to 6 of 6

Thread: dynamic number of columns

  1. #1
    Join Date
    May 2005
    Posts
    10

    Question dynamic number of columns

    when using sorred procedure to create a temporary table is it possable to base the number of columns in that table on another variable?

  2. #2
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254

  3. #3
    Join Date
    Feb 2003
    Posts
    1,048
    Like MAK, I'm not sure I quite understand the question, but you can create your "Create Table" statement dynamically and then execute the statement using either Exec() or sp_executesql.

  4. #4
    Join Date
    May 2005
    Posts
    10

    example

    for example
    --asume a loop for each account_number
    declare @tbl
    (
    account_number int,
    term int,
    month1 money,
    --and here is where the number of months columns is what would very for each account_number.
    some accounts would only be 6 months and some 60
    )

    select * from @tbl

    hope this is clear enough...?

  5. #5
    Join Date
    Feb 2003
    Posts
    1,048
    Declare @SQL nvarchar(4000),
    @Months int,
    @counter int

    Set @Months = 12
    Set @counter = 1
    Set @SQL = 'Create Table dbo.MyTable (account_number int not null, term int not null'

    While @counter <= @Months
    Begin
    Set @SQL = @SQL + ', month' + Cast(@counter as nvarchar) + ' money null'

    Set @counter = @counter + 1
    End

    Set @SQL = @SQL + ')'

    Exec sp_executesql(@SQL)



    select * from @tbl

  6. #6
    Join Date
    May 2005
    Posts
    10
    Perfect, I will give this a try.
    FYI.
    Thank you this is my first time using this forum and am very impressed with the speed of response!!

    Hope I can help some one else in the same way.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •