sql - Populating a Datetime Column -
i want populate datetime column on fly within stored procedure. below query have same slows down query performance.
create table #taxval ( id int , paiddate datetime , custid int , compid int ) insert #taxval(id, paiddate, custid, compid) values(01, '20150201',12, 100) , (03,'20150301', 18,101) , (10,'20150401',19,22) , (17,'20150401',02,11) , (11,'20150411',18,201) , (78,'20150421',18,299) , (133,'20150407',18,101) -- select * #taxval declare @startdate datetime = '20150101' , @enddate datetime = '20150501' declare @tab table ( compid int , datefield datetime ) declare @t int set @t = 0 while @enddate >= @startdate + @t begin insert @tab select compid , @startdate + @t datefield #taxval custid = 18 , compid = 101 order datefield desc set @t = @t + 1 end select distinct * @tab drop table #taxval
which best way write query better performance?
change this:
declare @t int set @t = 0 while @enddate >= @startdate + @t begin insert @tab select compid , @startdate + @t datefield #taxval custid = 18 , compid = 101 order datefield desc set @t = @t + 1 end
to this:
;with cte as( select cast('20150101' date) d union select dateadd(dd, 1, d) d cte d < '20150501' ) insert @tab select compid, d #taxval cross join cte custid = 18 , compid = 101 option(maxrecursion 0)
here recursive common table expression
dates in range. cross join
, insert. notice there no sense order set while inserting.
Comments
Post a Comment