converting Year and Month varchar to date

  • I have a table with Month , Year as varchar. I realized it was a big mistake. Since its getting too complicated to query this way.

    Year Month Productname

    2013 11 ACB

    2013 11 CDE

    I would now like to add another column called date and store these Year Month as a date to my existing table

    Year Month ProductName Date

    2013 11 ACB 2013-11-01

    2013 11 CDE 2013-11-01

    Is there a way I can do it for all the columns of the existing table ??

    Please let me know

  • You can add a derived column on the table with a formula as used below:

    WITH SampleData([Year], [Month], Productname ) AS(

    SELECT '2013', '11', 'ACB' UNION ALL

    SELECT '2013', '11', 'CDE'

    )

    SELECT *, CAST( [Year] + [Month] + '01' AS date)

    FROM SampleData

    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 (1/31/2014)


    You can add a derived column on the table with a formula as used below:

    WITH SampleData([Year], [Month], Productname ) AS(

    SELECT '2013', '11', 'ACB' UNION ALL

    SELECT '2013', '11', 'CDE'

    )

    SELECT *, CAST( [Year] + [Month] + '01' AS date)

    FROM SampleData

    And make sure the column is a PERSISTED column so that you can index it and the column isn't recalculated every time you read it.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Try

    ALTER TABLE table

    ADD [Date] date;

    go

    UPDATE table

    set [Date]= DateFromParts(cast([Year] as int), cast([Month] as int), 1);

    go

    /*

    ALTER TABLE table

    DROP COLUMN [Year], [Month];

    */

    or

    ALTER TABLE table

    add [Date] as DateFromParts(cast([Year] as int), cast([Month] as int), 1) persisted;

Viewing 4 posts - 1 through 3 (of 3 total)

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