Convert numeric to date

  • Hi there,

    I have spent days working on this, and I'm just not getting anywhere, so I would appreciate some help, or some hints..

    I have a column that is numeric 9, that stores dates in the format YYYYMMDD, and I would like to perform date arithmetic on this column (eg, getdate() - 30).

    Any ideas?

    thanks.

     

  • This will do it:

    PRINT CAST(CAST(20070105 as VARCHAR(8)) AS SMALLDATETIME)

    Be wary of the overhead this will add in a query.

    SQL guy and Houston Magician

  • thanks - I'll give it a go!

  • Don't use "getdate() - 30". Use the DateAdd() function.


    My blog: SQL Soldier[/url]
    SQL Server Best Practices:
    SQL Server Best Practices
    Twitter: @SQLSoldier
    My book: Pro SQL Server 2008 Mirroring[/url]
    Microsoft Certified Master: SQL Server, Data Platform MVP
    Database Engineer at BlueMountain Capital Management[/url]

  • You should also consider to change the datatype to a datetime, then all 'number to date problems' goes away.

    If you have data that is a date, it should be treated as a date also.

    /Kenneth

  • If you absolutely MUST have your date stored in YYYYMMDD format, then why not create another column in the table that simultaneously records the same date in the more traditional smalldatetime datatype?

    Then you have the best of both worlds!


  • ...and taking that a small step further, make it a persisted computed column, so it's done once and automatically with application involvement.



    Mark

  • That's what I would do. I would store the value as a datetime or smalldatetime and then use a persisted computed column for the integer value. Like so:

    MyDate smalldatetime NOT NULL

    iMyDate  AS (CONVERT(int,CONVERT(varchar, MyDate,(112)),0)) PERSISTED


    My blog: SQL Soldier[/url]
    SQL Server Best Practices:
    SQL Server Best Practices
    Twitter: @SQLSoldier
    My book: Pro SQL Server 2008 Mirroring[/url]
    Microsoft Certified Master: SQL Server, Data Platform MVP
    Database Engineer at BlueMountain Capital Management[/url]

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

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