Last active
January 13, 2021 22:50
-
-
Save stevewithington/09ef598e3a9dfeb5e47b11bd02eba5a4 to your computer and use it in GitHub Desktop.
SQL: UDF to convert string to date or return '0001-01-01'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SET ANSI_NULLS ON | |
GO | |
SET QUOTED_IDENTIFIER ON | |
GO | |
-- ============================================= | |
-- Author: <[email protected]> | |
-- Create date: 2020.12.21 | |
-- Description: Convert string to DATE if NULL or invalid, else set to '0001-01-01' | |
-- ============================================= | |
CREATE FUNCTION [dbo].[udf_ConvertStringToDate] | |
( | |
@Field VARCHAR(500) | |
) | |
RETURNS DATE | |
AS | |
BEGIN | |
DECLARE @StrField VARCHAR(500) = CAST(@Field AS VARCHAR(500)); | |
IF ISDATE(@StrField) = 0 | |
BEGIN | |
SET @StrField = '0001-01-01'; | |
END | |
RETURN CONVERT(DATE, @StrField); | |
END | |
GO | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment