Fix Bad Date
CREATE FUNCTION [dbo].[ufn_utl_FixBadDate]
(
@StringDate VARCHAR(12)
)
RETURNS DATE
AS
BEGIN
DECLARE @DateValue DATE;
IF LEN(@StringDate) > 1
BEGIN
DECLARE @DayDate CHAR(2);
DECLARE @Month CHAR(2);
DECLARE @Year VARCHAR(4);
SET @DayDate = RIGHT('00' + ISNULL(SUBSTRING(@StringDate, 1, CHARINDEX('/', @StringDate) - 1), ''), 2);
DECLARE @monthYear VARCHAR(100) = SUBSTRING(@StringDate, CHARINDEX('/', @StringDate) + 1, 100);
SET @Month = RIGHT('00' + ISNULL(SUBSTRING(@monthYear, 1, CHARINDEX('/', @monthYear) - 1), ''), 2);
SET @Year = RIGHT('20' + ISNULL(SUBSTRING(@monthYear, CHARINDEX('/', @monthYear) + 1, 100), ''), 4);
SET @DateValue = CONVERT(DATE, @DayDate + '/' + @Month + '/' + @Year, 103);
END;
ELSE
BEGIN
SET @DateValue = NULL;
END;
RETURN (@DateValue);
END;
GO
Comments
Post a Comment