Home Forums SQL Server 2008 T-SQL (SS2K8) Problem with CAST to VARCHAR with SUBSTRING Function RE: Problem with CAST to VARCHAR with SUBSTRING Function

  • Welsh Corgi (1/19/2013)


    I'm haveing trouble with a simple CAST to VARCHAR Statement.

    SELECT

    CASE WHEN CAST(LEFT(Customer.STARTDATE, 2 AS VARCHAR(2)))

    = '98' THEN CAST(substring(Customer.STARTDATE, 3, 2) AS VARCHAR(2))

    WHEN LEFT(CAST(Customer.STARTDATE, 2) AS VARCHAR(2)) = '99' THEN

    CAST(substring(Customer.STARTDATE, 3, 2) AS VARCHAR(2)) END AS LossMo

    FROM Customer

    Any help would be greatly apreciated.

    It's roughly equivalent to this:

    SELECT

    c.STARTDATE,

    LossMo = CASE

    WHEN x.thingy IN ('98','99') THEN x.AnotherThingy

    ELSE NULL END

    FROM Customer c

    CROSS APPLY (

    SELECT

    Thingy = CAST(LEFT(c.STARTDATE, 2 AS VARCHAR(2))),

    AnotherThingy = CAST(substring(c.STARTDATE, 3, 2) AS VARCHAR(2))

    ) x

    which is a little confusing...

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden