October 15, 2014 at 3:37 am
Hi Everyone.
Does anyone have a UDF that accepts a Month and Year and returns Start Date and End Date.
For example @Month = 01 and @Year = 2014 would return a StartDate of 2014-01-01 and an EndDate of 2014-01-31.
Thanks for your help
October 15, 2014 at 3:55 am
Just to get you started: have look at the DATEADD function (http://msdn.microsoft.com/de-de/library/ms186819.aspx).
You can make use of the fact that 0 corresponds to 01-01-1900.
A final hint: The last day of the month is one day before the first day of the next month.
October 15, 2014 at 3:59 am
Use dates functions, dateadd() namely.
declare @Month varchar = '01'
declare @Year varchar = '2014'
select starDt = CAST(@Year + @Month +'01' as Date), endDt = dateadd(dd,-1,dateadd(mm,1, CAST(@Year + @Month +'01' as Date)))
Or the question is about UDF syntax?
October 15, 2014 at 4:02 am
Thanks for that. Can you please provide as UDF?
October 15, 2014 at 4:10 am
Look at inline TVF http://technet.microsoft.com/en-us/library/ms189294(v=sql.105).aspx
October 15, 2014 at 4:16 am
Thanks for that. I tried the following code below but it returned the wrong answer. Do you have any further suggestions:
declare @Month varchar = '02'
declare @Year varchar = '2014'
select StartDate = CAST(@Year + @Month +'01' as Date)
,endDt = dateadd(dd,-1,dateadd(mm,1, CAST(@Year + @Month +'01' as Date)))
October 15, 2014 at 6:21 am
ganteng1 (10/15/2014)
Thanks for that. I tried the following code below but it returned the wrong answer. Do you have any further suggestions:declare @Month varchar = '02'
declare @Year varchar = '2014'
select StartDate = CAST(@Year + @Month +'01' as Date)
,endDt = dateadd(dd,-1,dateadd(mm,1, CAST(@Year + @Month +'01' as Date)))
You forgot to size your variables. CHAR is more appropriate also:
DECLARE @Month CHAR(2) = '02'
DECLARE @Year CHAR(4) = '2014'
SELECT
StartDate,
EndDt = DATEADD(dd, -1, DATEADD(mm, 1, StartDate))
FROM (SELECT StartDate = CAST(@Year + @Month +'01' AS DATE)
) d
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
October 16, 2014 at 3:43 am
Thanks for all of your help
October 16, 2014 at 8:36 am
If the parameters are integers
DECLARE @Month int = 2
DECLARE @Year int = 2014
SELECT
DATEADD(month,(@Year*12-22800)+(@Month-1),0) AS [SatrtDate],
DATEADD(daY,-1,DATEADD(month,(@Year*12-22800)+@Month,0)) AS [EndDate]
Far away is close at hand in the images of elsewhere.
Anon.
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply