sql server 2008 - How can I get Month Difference from two dates which are stored in Table in the format YYYYMM -
my table has column date_period stores date in format yyyymm. want write query inserts date in date_period column in format yyyymm if there no entry till current month.
for example: date period has entry till october 2015 contain value 201510. want check , insert data till current month if not present. entries 201511, 201512, 201601
how can achieve this?
try way, may you
declare @v date= getdate() declare @currentdate varchar(10) set @currentdate=convert(varchar(10), @v, 112) /*@currentdate string in format '20160129'*/ if not exists(select * table1 date_period=left(@currentdate,6)) begin insert table1(date_period)values(left(@currentdate,6)) end
try this
i think complete solution problem
declare @monthcount int declare @v date= getdate() declare @lastsavedmonth varchar(20)= (select max(date_period) table1) declare @lastsaveddate varchar(20)= @lastsavedmonth+''+right(convert(varchar, 100 + datepart(d,@v)), 2) set @monthcount=datediff(month,@lastsaveddate,convert(varchar(10), @v, 112)) while @monthcount>=0 begin declare @dateofsavingmonth varchar(20) if(@monthcount=0) begin set @dateofsavingmonth=convert(varchar(10),@v,112) end else begin set @dateofsavingmonth=convert(varchar(10), dateadd(month,-@monthcount,@v),112) end if not exists(select * table1 date_period=left(@dateofsavingmonth,6)) begin insert table1(date_period)values(left(@dateofsavingmonth,6)) end set @monthcount =@monthcount-1 end
Comments
Post a Comment