Sunday, February 26, 2012

Dynamic creation of columns

Scenario:
I would like to create a New table named orders_table.
Since the user can choose how many products he wants.
if he choose 3 the table should be 3 columns
if he choose 44 the table should be 44 columns and so on. Is this possible?

So, for your scenario, there would have to be a new table for each user, because one table can only have a certain number of columns. You may want to consider creating a record in one table for each product the user chooses. If you are determined to create one for every user, then you could do something like this:

declare @.userproductcount int, @.i int
declare @.tblname varchar(10)
declare @.string varchar(8000)
set @.userproductcount = 5
set @.tblname = 'test'
set @.i = 1
set @.string = 'create table ' + @.tblname + ' ('

while @.i <= @.userproductcount
begin
set @.string = @.string + 'fldname' + + cast(@.i as varchar(10)) + ' int' + case when @.i = @.userproductcount then ')' else ',' end
set @.i = @.i + 1
end

exec @.string|||This sounds like a pretty bad idea, personally. Is this a result set? You shouldn't create a table based on what a user wants.

No comments:

Post a Comment