Converting a CHAR to DATETIME

  • I have scanned all the forums I could, but couldn't find anything related to my problem.

    I am trying to convert a CHAR(6) to DATETIME, and am having a bugger of a time.

    My CHAR(6) field contains a date in the format YYYYMM. I want to convert that to a DATETIME keeping the same format (YYYYMM).

    How can I do that? Any help is greatly appreciated.

    Thanks,

    Byron

  • Not sure you can do both, what are you trying to accomplish?

    You could try to parse but I know of no date format that will directly support YYYYMM in sql server.

    "Don't roll your eyes at me. I will tape them in place." (Teacher on Boston Public)

  • I am trying to calculate a date range based off the value in my CHAR(6) column.

    For example: council_date is defined as CHAR(6). Sample values are 200201, 200202, etc..

    The table they exist on contains many years of data. I want to select only those council_dates that are greater than one month minus the current council_date.

    So if I have: 200201, 200202, 200203, 200204, 200205, 200206. I want a selection clause that will only return dates 200204 and greater.

    I am trying to keep this a calculated result set based of the current date. Does this make sense?

  • I'm not sure I understood it well.

    But if you have CHAR(6) format for yyyymm, the maybe you could search this way:

    1. Make up a string as:

    Concatenate current year + current month.

    Ex. 200205

    2. Turn it to a number (use CAST Function)

    Ex. Select @YourNumber = CAST (string,int)

    3. Compare in your select as

    SELECT (council_date FROM table

    where CAST(council_date , int) > @yournumber

    Well, at least i tried

  • Try

    SELECT

    *

    FROM

    tblX

    WHERE

    council_date >= DATEPART(yyyy,DATEADD(mm,-1,GETDATE())) * 100 + DATEPART(mm,DATEADD(mm,-1,GETDATE()))

    If council_date is not an int the adjust with CAST(council_date AS INT)

    "Don't roll your eyes at me. I will tape them in place." (Teacher on Boston Public)

  • Thank you very much for the assistance. The code sample you supplied worked great.

    -Byron

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

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