0

I need to extract the month and year in SQL Server. For example if the date is 2015-01-01, I want to make it 201501 and convert it to varchar(6)

How do I do this?

2
  • 3
    Try this: SELECT CONVERT(VARCHAR(6), CAST('2015-01-01' AS DATE),112) Commented Mar 20, 2015 at 4:34
  • 1
    Welcome to Stack Overflow! Please search first before asking a new question. Commented Mar 20, 2015 at 5:08

5 Answers 5

2
1. SELECT CONVERT(VARCHAR(6), GETDATE(), 112) 2. SELECT CAST(YEAR(GETDATE()) * 100 + MONTH(GETDATE()) AS VARCHAR(6)) 
Sign up to request clarification or add additional context in comments.

1 Comment

this one is different and smart :)
2

Try this:

SELECT DATEPART(yyyy, @date) * 100 + DATEPART(mm, @date) 

If you want to do the operation on the current time then replace @date with CURRENT_TIMESTAMP.

The result is integer though, you may convert it to varchar(6) using CAST() or CONVERT() method.

Comments

1

Try.. FIDDLE DEMO

declare @dt datetime='2015-01-01' select CAST(YEAR(@dt)as Varchar(6))+ Case When Len(Cast(MONTH(@dt) as varchar(6)))>1 then CAST(MONTH(@dt) as varchar(6)) Else '0'+Cast(MONTH(@dt) as varchar(6)) End 

EDIT:2

declare @dt date='2015-01-01' select CAST(REPLACE(@dt,'-','')as varchar(6)) 

Comments

1

This is the simplest answer

select getdate() , convert( varchar(6) , getdate() ,112) 

and if you want year as 2 digit

select getdate() , convert( varchar(12) , getdate() ,12) 

Whenever you want to convert date format from standard format to another format, always check this link.

http://www.w3schools.com/sql/func_convert.asp

https://msdn.microsoft.com/en-us/library/ms187928.aspx

Comments

0
select CONVERT(nvarchar(6), DATENAME(yyyy, getdate())) + SUBSTRING(CONVERT(nvarchar(6),getdate(), 112),5,2) 

DATENAME:

Returns a character string that represents the specified datepart of the specified date

ref:

https://msdn.microsoft.com/en-IN/library/ms174395.aspx

for all datetime conversion this will help

http://www.sqlusa.com/bestpractices/datetimeconversion/

2 Comments

not gonna work. Expected result is 201501
@user3540365 Please see updated answer getting 201503

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.