Select Datepart

  • Is there a way for me to use the Datepart function so that it would return today's date as:

    20060619

    Or is there another way I can do it?

    The below didn't quite get me what I needed.

    SELECT DATEPART(YYYY, GETDATE()), DATEPART(MM,GETDATE()) , DATEPART(DD, GETDATE())

    Thanks!

  • print convert(varchar,@datetime,112)

    John Rowan

    ======================================================
    ======================================================
    Forum Etiquette: How to post data/code on a forum to get the best help[/url] - by Jeff Moden

  • Yes, there is. This code will do what you need:

    SELECT

    Cast(Datepart(yyyy, GetDate()) AS char(4)) +

    Right('0' + Cast(DatePart(mm, GetDate()) AS Varchar(2)), 2) +

    Right('0' + Cast(DatePart(dd, GetDate()) AS Varchar(2)), 2)

  • That worked great, thanks!

  • I just realized that I pasted the wrong section into my post.

    This returns the same result as Brendt's DatePart/Cast example, but with less function calls:

    SELECT CONVERT(varchar,GETDATE(),112)

    John Rowan

    ======================================================
    ======================================================
    Forum Etiquette: How to post data/code on a forum to get the best help[/url] - by Jeff Moden

  • Perhaps, but the questioner specifically requested a method using DatePart. I use this when generating a YYYYMMDDHHNN strings, in preference to stripping formatting out of a CONVERTed datetime, because it is far more readable.

  • Of course, I never noticed the "Or is there some other way to do it" portion of the post 😯

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply