Need SQL help with this datetime query

MisterBigglesworth

Expert Member
Joined
Aug 15, 2006
Messages
3,334
Reaction score
13
Location
/\\/¯¯¯\//\
Hi,

I dont know what I'm doing wrong. Have done stuff like this countless times, and no issues. But now the below wont run, I keep getting an error:

Msg 245, Level 16, State 1, Line 22
Conversion failed when converting the varchar value '1 May ' to data type int.


The code basically gets the previous and current month names, with their years and the last line adds a '1 ' to the front to build a custom date string.

Code:
DECLARE
@StartMonthDate			DATETIME,
@EndMonthDate			DATETIME,
@StartMonth				VARCHAR(50),
@EndMonth				VARCHAR(50),
@StartYear				INT,
@EndYear				INT

--get previous month and current month date
SET @StartMonthDate = DATEADD(MM, -1, GETDATE())
SET @EndMonthDate = GETDATE()

--get month name of each
SET @StartMonth = DATENAME(MONTH, @StartMonthDate)
SET @EndMonth = DATENAME(MONTH, @EndMonthDate)

--get year of each
SET @StartYear = YEAR(@StartMonthDate)
SET @EndYear = YEAR(@EndMonthDate)

--display custom start date in format: 1 May 2011
SELECT CAST('1 ' + @StartMonth + ' ' + @StartYear AS VARCHAR(50))

What is wrong with the code that it wont execute the query? I think my brain is fried and I suspect it's the simplest of things... :confused:
 
StartYear is an int. Either declare it as varchar or cast it and it should work.
 
Top
Sign up to the MyBroadband newsletter
X