SQL Query Syntax

I have a date field e.g. 2016-01-06 00:00:00.000
I need to convert it to MM-YYYY so it sorts a-z in Excel.

Anyone know the syntax?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Sam Simon NasserIT Support ProfessionalCommented:
HKFueyAuthor Commented:
OK, I have this: -
CAST(DATEPART(YYYY, TransactionDate) AS VARCHAR(4)) + '-' + CAST(DATEPART(MM, TransactionDate) AS VARCHAR(2))
Which gives 2018-3, but I would like it to read 2018-03
SharathData EngineerCommented:
check this.
declare @date datetime
select @date = '2016-01-06 00:00:00.000'

-- 01-2016, 2016-01

Open in new window

OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

As Sam said, convert it to a varchar, with say format 121, but add the varchar size to trim the results to yyyy-mm

SET @myDateTime = '2016-01-06 00:00:00.000'
SELECT CONVERT(VARCHAR(7), @myDateTime, 121)

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Sam Simon NasserIT Support ProfessionalCommented:
check this document from Microsoft regarding Date and Time Styles
HKFueyAuthor Commented:
Thanks for the speedy help!
PortletPaulEE Topic AdvisorCommented:
Since SQL Server 2012 it is possible to use FORMAT()

    it is a lot easier to use 'yyyy-MM' than it is to remember "121 truncated to 7 chars " (or similar)

SET @myDateTime = '2016-01-06 00:00:00.000'
    FORMAT(@myDateTime,'yyyy-MM')         as by_format
  , CONVERT(VARCHAR(7), @myDateTime, 121) as by_convert

Open in new window

If you really need to use the older CONVERT() method this article may help:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.