sql - Dynamically create column in Table -
i have create table within procedure. have start date , end date value. want create columns date range if start date 15 july 2013 , end date 18 july 2013 there 4 columns(july1,july2,july3,july4) created.
how can achieve this. have used sql server 2008.. please me.....
sir front end have fromdate , todate fields on submit have called sp c# code, want create table within proc. table must have no. of columns no. of days exists between given dates.
try this:
declare @dtmin date declare @dtmax date declare @dynsql nvarchar(3000) declare @colname varchar(20) set @dynsql = n'create table trial(' set @dtmin = {d '2013-07-15'} set @dtmax = {d '2013-07-18'} declare @currdate date set @currdate = @dtmin while (@currdate <= @dtmax) begin set @colname = datename(month, @currdate) + convert(varchar, datepart(day, @currdate)) set @dynsql = @dynsql + @colname + ' varchar(10)' if (@currdate < @dtmax) begin set @dynsql = @dynsql + ', ' end else begin set @dynsql = @dynsql + ')' end set @currdate = dateadd(day, 1, @currdate) end exec sp_executesql @dynsql
p.s.: don't know reason of request, not correct create table in way because information want put columns, should put in rows.
example: if want store sales day day, correct table, named sales, is: sales (id varchar(36), dt datetime, amount decimal(19,2)) instead of sales (id varchar(36), dt1 decimal(19,2), dt2 decimal(19,2)... , on)
because if want change period must rewrite table, if want query table must write several queries each situation. it's hard work on table.
please, reconsider choice.
have nice day.
Comments
Post a Comment