Changing Datetime to Int and set it to beginning of month

  • Hi Guys and Girls,

    I have the following:

    SELECT CAST(CONVERT(VARCHAR(8), GETDATE(), 112) AS INT)

    SELECT DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0)

    The first sets getdate() to an int.

    The second set the date to the first of the month.

    Does anyone have an idea how I can combine the two to set the date to the beginning of the month but still as an integer?

    Kind regards

    Fred

  • SELECT YEAR(GETDATE()) * 10000 + MONTH(GETDATE()) * 100 + 1;

    Need an answer? No, you need a question
    My blog at https://sqlkover.com.
    MCSE Business Intelligence - Microsoft Data Platform MVP

  • Thanks Koen.

  • For consistency, I'd stick with just explicitly CASTing the second value to an int:

    SELECT CAST(DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AS int)

    SQL DBA,SQL Server MVP(07, 08, 09) "It's a dog-eat-dog world, and I'm wearing Milk-Bone underwear." "Norm", on "Cheers". Also from "Cheers", from "Carla": "You need to know 3 things about Tortelli men: Tortelli men draw women like flies; Tortelli men treat women like flies; Tortelli men's brains are in their flies".

  • ScottPletcher (10/7/2014)


    For consistency, I'd stick with just explicitly CASTing the second value to an int:

    SELECT CAST(DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AS int)

    I agree with you, but you missed the intermediate convert.

    SELECT CAST(CONVERT( char(8), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0), 112) AS int)

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • Luis Cazares (10/7/2014)


    ScottPletcher (10/7/2014)


    For consistency, I'd stick with just explicitly CASTing the second value to an int:

    SELECT CAST(DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AS int)

    I agree with you, but you missed the intermediate convert.

    SELECT CAST(CONVERT( char(8), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0), 112) AS int)

    Hmm, but no intermediate conversion is needed. Dates already are ints, and ints are de facto dates.

    SQL DBA,SQL Server MVP(07, 08, 09) "It's a dog-eat-dog world, and I'm wearing Milk-Bone underwear." "Norm", on "Cheers". Also from "Cheers", from "Carla": "You need to know 3 things about Tortelli men: Tortelli men draw women like flies; Tortelli men treat women like flies; Tortelli men's brains are in their flies".

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

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