Home Forums SQL Server 2008 T-SQL (SS2K8) Using CAST or CONVERT to change data from string to datetime RE: Using CAST or CONVERT to change data from string to datetime

  • I suggest:

    1) be sure to pad the month and day values so that the final format is a full yyyymmdd.

    2) apply column names to make the code easier to understand and maintain

    3) use CAST() as it will always accept 'yyyymmdd' with no conversion code required.

    SELECT CAST(Field1_year + Field1_month + Field1_day AS datetime)

    FROM ( --dbo.tablename

    SELECT '160416' AS Field1

    ) AS a1

    CROSS APPLY (

    SELECT

    '20' + LEFT(a1.Field1,2) AS Field1_year,

    RIGHT('0' + SUBSTRING(a1.Field1,3,2), 2) AS Field1_month,

    RIGHT('0' + SUBSTRING(a1.Field1,5,2), 2) AS Field1_day

    ) AS ca1

    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".