Reputation: 310
I am trying to produce a varchar(20) which is 4 character year + 2 character month. I would like to then use this as a parameter in my stored procedure. Im unable to concatenate 2 varchars together to produce this, any ideas?
SELECT
GETDATE() AS CurrentDateTime,
CONVERT(VARCHAR(20), YEAR(GETDATE())) AS CurrentYear,
CONVERT(VARCHAR(20), MONTH(GETDATE())) AS CurrentMonth,
CurrentYear + CurrentMonth AS YearMonth
Upvotes: 0
Views: 208
Reputation: 124
Like this one?
SELECT GETDATE() AS CurrentDateTime
, Convert(VARCHAR(20),YEAR(GETDATE())) AS CurrentYear
, Convert(VARCHAR(20),MONTH(GETDATE())) AS CurrentMonth
, Convert(VARCHAR(20),YEAR(GETDATE())) + Convert(VARCHAR(20),MONTH(GETDATE())) AS YearMonth
Also you can
Year(GetDate()) * 100 + Month(GateDate()) AS YearMonth
or use construction which offered by users below
Convert(varchar(6), GETDATE(), 112) AS YearMonth
Upvotes: 0
Reputation: 24247
The simplest approach would be to use this:
SELECT Format(GetDate(), 'yyyyMM') as YearMonth
The function Format()
was introduced with Sql Server 2012.
Upvotes: 6
Reputation: 24783
why not simply
SELECT GETDATE() AS CurrentDateTime
, Convert(VARCHAR(20),YEAR(GETDATE())) AS CurrentYear
, Convert(VARCHAR(20),MONTH(GETDATE())) AS CurrentMonth
, Convert(varchar(6), GETDATE(), 112) AS YearMonth
Upvotes: 3
Reputation: 2651
SELECT GETDATE() AS CurrentDateTime
, Convert(VARCHAR(20),YEAR(GETDATE())) +
Convert(VARCHAR(20),MONTH(GETDATE()))
Column aliases can't be selected from, so the above would do.
Upvotes: 1