Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to create columns automatically in sql server 2008 based on start date and end date

this is my table
SQL
create table demotable
(
Id int primary key identity(1,1),
Name varchar(50),
StartDate date,
EndDate	date
)



SQL
declare @dates int, @StartDate  datetime, @EndDate datetime
 
---Here, we assume that,
Select   @StartDate  = convert(datetime, '1/7/2015'), @endDate = convert(datetime,'1/10/2015')
 
select @dates = datediff (dd,@StartDate ,@Enddate)
 
 ---Now add columns by dynamically with while loop
 
 While (@dates >0)
begin
   alter table  demotable add [Columnname] datetime
   select @dates  =  @dates - 1
end 




if i executes this code a column(columnname) is adding to my sql table with showing a error
*Column names in each table must be unique. Column name 'Columnname' in table 'demotable' is specified more than once.
*

i want to add no of months columns from start date to end date
Posted
Updated 23-Jul-15 23:48pm
v2

1 solution

As I explained in previous answer: How to create new table on every drop down list item select[^] this is most likely a really bad thing to do.

However, if you really need to do this for some reason you must make sure that every column is named differently. So build the ALTER TABLE command dynamically and execute it. Something like
SQL
declare @command nvarchar(max)
declare @dates int, @StartDate  datetime, @EndDate datetime
 
---Here, we assume that,
Select   @StartDate  = convert(datetime, '1/7/2015'), @endDate = convert(datetime,'1/10/2015')
 
select @dates = datediff (dd,@StartDate ,@Enddate)
While (@dates >0) begin
    set @command  = 'alter table demotable add [Columnname' + cast(@dates as nvarchar(max)) + '] datetime'
   exec sp_executesql @command
   select @dates  =  @dates - 1
end


But as said this design will probably cause problems in the future.
 
Share this answer
 
Comments
Member 11382784 30-Jul-15 1:43am    
thanks for your help sir,
in output of this code am getting table columns as
... columnname3 columnname2 columnname1
i want like 1/7/2015 1/8/2015 1/9/2015...
i have tried but iam not getting sir please help me
Wendelius 30-Jul-15 3:32am    
I have to repeat the warning, this design is going to cause you a lot of trouble. Believe me, it would be better to properly normalize the table structure.

Having that said, you can replace the command with

set @command = 'alter table demotable add [' + convert(varchar(100), dateadd(day, @dates, @StartDate ), 1) + '] datetime'

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900