I have created a T-SQL function that is able to extract dates from strings.
The function works when the date has no ..
Please help get the missing piece to make this function work with dates that have periods.
Dates with periods come in 2 different flavors:
MM.DD.YYYY
M.DD.YY
My function code:
IF OBJECT_ID(N'tempdb..#fileNameTable', N'U') IS NOT NULL
DROP TABLE #fileNameTable
CREATE TABLE #fileNameTable
(
[fName] [VARCHAR](250) NULL
)
INSERT INTO #fileNameTable (fName)
SELECT '9999999991_Agent Name_08.02.2018.WAV'
INSERT INTO #fileNameTable (fName)
SELECT '9999999999 - Internal ID 1446683 (Pedro) 6.26.17 WB.mp3'
INSERT INTO #fileNameTable (fName)
SELECT '9999999998 - Internal ID 1464807 (John) 7.11.17.mp3'
INSERT INTO #fileNameTable (fName)
SELECT '9999999997 - Internal ID 1447503 (Marta) 6.27.17.mp3'
INSERT INTO #fileNameTable (fName)
SELECT '9999999996 - Internal ID 1437403 (Ruby) 6.20.17.mp3'
INSERT INTO #fileNameTable (fName)
SELECT 'rc_20200817_1612_9999999995_NJ.wav'
INSERT INTO #fileNameTable (fName)
SELECT 'rc_20200817_1543_9999999994_PA.wav'
INSERT INTO #fileNameTable (fName)
SELECT 'rc_20200817_1211_9999999993_MA.wav'
INSERT INTO #fileNameTable (fName)
SELECT 'rc_20200817_1211_9999999992_MD.wav'
SELECT *, [dbo].[ExtractDateFromFileName](fName)
FROM #fileNameTable
CREATE FUNCTION [dbo].[ExtractDateFromFileName]
(@str VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @validchars VARCHAR(MAX)
SET @validchars = '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
DECLARE @idx INT
SET @idx = PATINDEX('%'+ @validchars +'%',@str)
IF @idx > 0 AND (@idx = LEN(@str) - 8
OR PATINDEX(SUBSTRING(@str, @idx + 9, 1), '[0-9]') = 0)
SET @str = SUBSTRING(@str, PATINDEX('%' + @validchars +'%', @str), 8)
ELSE
SET @str = ''
RETURN @str
END
.characters into your matching pattern. Your next problem is that your dates aren't formatted consistently - some use themm-dd-yyyypattern, others seem to bem-d-yypattern, still others use theyyyymmddpattern. SQL Server is really bad/inefficient for data extraction like this, you'd be better served using an external scripting language that's fit-for-purpose like Perl, NodeJS, Python, PowerShell etc., all of which have regex support.