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) A socialist is someone who will give you the shirt off *someone else's* back.