how to convert varchar value to datetime

  • SELECT MAX(CASE code WHEN 'sdt' THEN convert(datetime,Cval) ELSE NULL END) as MinDate,

    MAX(CASE code WHEN 'Edt' THEN convert(datetime,Cval) ELSE NULL END) as MaxDate

     from table

    Cval in table is varchar(20). value holds in this column is '2015034' Now I have to compare this coulm value to datetime valve for that in the query how Cval column will be converted to datetime?

  • mcfarlandparkway - Thursday, February 23, 2017 10:58 AM

    SELECT MAX(CASE code WHEN 'sdt' THEN convert(datetime,Cval) ELSE NULL END) as MinDate,

    MAX(CASE code WHEN 'Edt' THEN convert(datetime,Cval) ELSE NULL END) as MaxDate

     from table

    Cval in table is varchar(20). value holds in this column is '2015034' Now I have to compare this coulm value to datetime valve for that in the query how Cval column will be converted to datetime?

    If I had to convert 2015034 to a date, I wouldn't have a clue how to do it. Can you explain?

    If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.

  • My best guess is that the value is a pseudo-"Julian" date (as IBM called it), i.e., that the last 3 digits are the relative day number of the year.

    IF that's true, you can do this:


    SELECT DATEADD(DAY, CAST(RIGHT(Cval, 3) AS int) - 1, LEFT(Cval, 4) + '0101') AS final_date
    FROM (
      VALUES('2015034')
    ) AS test_data(Cval)

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

  • Phil Parkin - Thursday, February 23, 2017 11:10 AM

    mcfarlandparkway - Thursday, February 23, 2017 10:58 AM

    SELECT MAX(CASE code WHEN 'sdt' THEN convert(datetime,Cval) ELSE NULL END) as MinDate,

    MAX(CASE code WHEN 'Edt' THEN convert(datetime,Cval) ELSE NULL END) as MaxDate

     from table

    Cval in table is varchar(20). value holds in this column is '2015034' Now I have to compare this coulm value to datetime valve for that in the query how Cval column will be converted to datetime?

    If I had to convert 2015034 to a date, I wouldn't have a clue how to do it. Can you explain?

    Wonder if its a year and some form of Julian date, possibly where 034 is representing the day of the year.

    --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)

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

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