I'm trying to extract a dollar value from a string using a mixture of substrings, charindexes, and patindexes. I can seem to extract the $###,###
pattern from all string except when it falls at the end of the string.
Here is some code with test cases:
CREATE TABLE #TMP
(
string VARCHAR(50)
)
GO
INSERT INTO #TMP
VALUES ('I have $4,000'),
('$44,450is what I have'),
('this $600 is what I have now'),
('$5 cause I am broke'),
('I have $10,000,000,000 '),
('No Money Here')
GO
SELECT
*,
SUBSTRING(string,
CHARINDEX('$', string),
PATINDEX('%[^0-9,]%', SUBSTRING(string, CHARINDEX('$', string) + 1, 80000))) AS Result
FROM
#TMP
DROP TABLE #TMP
GO
Results:
SQL Server version:
Microsoft SQL Server 2016 (SP1) (KB3182545) - 13.0.4001.0 (X64)
Just add an x (or any non-numeric character) to every instance of string
:
SELECT
*,
SUBSTRING(
string + 'x',
CHARINDEX('$',string + 'x'),
PATINDEX('%[^0-9,]%',SUBSTRING(string + 'x',CHARINDEX('$',string + 'x')+1, 80000))
) AS Result
FROM
#TMP