Consider a varchar field (ShipDate) that gets date-like strings written to it. These strings come from multiple third-party systems in various formats (over which I, apparently, have no control =/).
I decided to create a view that converts this varchar field to DATE so that I can query it easily (and filter out some other records / fields that I don’t care about).
So far I see two formats coming in: YYYYMMDD (which is fine, I can just a a straight CONVERT) and MM/DD/YYYY, which causes an error:
Conversion failed when converting date and/or time from character string.
This changes my conversion from a simple CONVERT(DATE, ShipDate, 1) to:
CONVERT (DATE,
(CASE
WHEN ShipDate LIKE '_/__/____' THEN SUBSTRING(ShipDate, 6, 4) + '0' + SUBSTRING(ShipDate, 1, 1) + SUBSTRING(ShipDate, 3, 2)--M/DD/YYYY
WHEN ShipDate LIKE '__/_/____' THEN SUBSTRING(ShipDate, 6, 4) + SUBSTRING(ShipDate, 1, 2) + '0' + SUBSTRING(ShipDate, 4, 1)--MM/D/YYYY
WHEN ShipDate LIKE '_/_/____' THEN SUBSTRING(ShipDate, 5, 4) + '0' + SUBSTRING(ShipDate, 1, 1) + '0' + SUBSTRING(ShipDate, 3, 1)--M/D/YYYY
ELSE ShipDate --For the YYYYMMDD dates
END), 1) --End of CONVERT
Is there a better way to do the above SQL statement? I could potentially get even more date-like string formats as time goes on, so the above example could get pretty awful (I tagged this question with regex in case that could reduce the size of the case statement).
Or, is there a way to handle this problem as the records come in, avoiding the view altogether? I’m not too familiar with Triggers / SP’s, but if that’s a good option I’m willing to go that route =)
Or, some other method that is commonly used to solve this problem? Just curious at this point. I’m a .NET programmer, but end up helping out with SQL work because I have some experience, so I’m pretty new to anything even kind of advanced in SQL.
If the known formats are always M then D, and the separators are always /, why not just parse for the slashes? Also, why are you using
,1)in yourCONVERT? All of the above formats seemed to convert fine for me without it: