sql server 2012 - sql datefromparts not working as expected -


i have following code:

declare @inddate date = '1/1/2014'  select  recordid rid,             name,              company,              phonenumber,              convert(varchar(10),dateofinduction,103) startdate,             convert(varchar(10),dateofexpiry,103) dateofexpiry     records dateofexpiry <= datefromparts(datepart(yyyy,@inddate),datepart(mm,@inddate),datepart(dd,dateadd(s,-1,dateadd(mm, datediff(m,0,@inddate)+1,0))))     , dateofexpiry >= datefromparts(datepart(yyyy,@inddate),datepart(mm,@inddate),1) 

which gives me expiring records month of @inddate parameter.

what trying add 1 month in datefromparts next month's values. don't want change @inddate other month because in report date not selected expires month, next month, previous month, etc.

so if change clause to:

where dateofexpiry <= datefromparts(datepart(yyyy,@inddate),datepart(mm,dateadd(mm,1,@inddate)),datepart(dd,dateadd(s,-1,dateadd(mm, datediff(m,0,@inddate)+1,0))))     , dateofexpiry >= datefromparts(datepart(yyyy,@inddate),datepart(mm,dateadd(mm,1,@inddate)),1) 

i error: cannot construct data type date, of arguments have values not valid. , not sure why, works fine if try like:

declare @inddate date = '1/1/2014' select dateadd(mm,1,@inddate) 

can see problem?

in error coming trying create date invalid date range,

if run parts of datefromparts in following manner

declare @inddate date = '1/1/2014' select datepart(yyyy, @inddate)        ,datepart(mm, dateadd(mm, 1, @inddate))        ,datepart(dd, dateadd(s, -1, dateadd(mm, datediff(m, 0, @inddate) + 1, 0))) 

this generates 2014 2 31 not valid date.

the following 3 examples give records previous, current or next month no matter if passed in '01/01/2014' or '01/15/2014'

this give records last month.

where dateofexpiry >= dateadd(month, -1,dateadd(dd,-datepart(day,@inddate)+1,@inddate)) , dateofexpiry < dateadd(dd,-datepart(day,@inddate)+1,@inddate) 

this give records current month

where dateofexpiry >= dateadd(dd,-datepart(day,@inddate)+1,@inddate)  , dateofexpiry < dateadd(month, 1,dateadd(dd,-datepart(day,@inddate)+1,@inddate)) 

finally records next month

where dateofexpiry >=  dateadd(month, 1, dateadd(dd, -datepart(day, @inddate) + 1, @inddate)) , dateofexpiry < dateadd(month, 2, dateadd(dd, -datepart(day, @inddate) + 1, @inddate)) 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -