Get data from a date range: Construct the start and end date – T-SQL




declare @StartMonth NVARCHAR(10),
@StartYear NVARCHAR(4),
@EndMonth NVARCHAR(10),
@EndYear NVARCHAR(4)

Select @StartMonth = N'January',
		@StartYear = N'2014',
		@EndMonth = N'February',
		--@EndMonth = N'December',
		@EndYear = N'2014'




Select Cast(@StartMonth + '1 ' + @StartYear as date) as beginningofstartdt
,Cast(@EndMonth + '1 ' + @EndYear as date) as beginningofenddt
,Dateadd(month,1,Cast(@EndMonth + '1 ' + @EndYear as date)) as beginningofNextMonth,
DateAdd(ms, -3, DateAdd(month, DateDiff(month, 0, Cast(@EndMonth + '1 ' + @EndYear as date))+1, 0) ) endofenddt


--Solutions for your question

WHERE ta.TimeByDay >= Cast(@StartMonth + '1 ' + @StartYear as date)
AND ta.TimeByDay <Dateadd(month,1,Cast(@EndMonth + '1 ' + @EndYear as date))

--Or

WHERE ta.TimeByDay >= Cast(@StartMonth + '1 ' + @StartYear as date)
AND ta.TimeByDay <=DateAdd(ms, -3, DateAdd(month, DateDiff(month, 0, Cast(@EndMonth + '1 ' + @EndYear as date))+1, 0) )


--
--new functions since SQL Server 2012 Datefromparts, Eomonth ...
 

http://social.msdn.microsoft.com/Forums/en-US/f4abec70-5278-42eb-9978-6305fd73ca06/selecting-records-based-on-month-and-year-parameters?forum=transactsql

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s