I am trying to extract the first numeric value to the right of the pattern LDL. I am trying to learn about SUBSTRING, PATINDEX and CHARINDEX. I am getting close, but in certain patterns(1 and 8 below) the return value truncates at 2 digits no matter the number of numeric digits.
Where am I going wrong? Stringing all the SUBSTRING and PATINDEX together gets confusing. I am open alternative SQL statements. As a side learning point, is there a best practice on how to wrap the statements to make it more readable?
Thank you in advance.
You don't know what you don't know...
Where am I going wrong? Stringing all the SUBSTRING and PATINDEX together gets confusing. I am open alternative SQL statements. As a side learning point, is there a best practice on how to wrap the statements to make it more readable?
Code:
IF OBJECT_ID('TEMPDB..#demo') IS NOT NULL DROP TABLE #demo
CREATE TABLE #demo(SubjectID int, TextResult varchar(100))
INSERT INTO #demo VALUES
(1, 'HDL is 30 and LDL 123')
,(2, 'go find it yourself')
,(3, '231')
,(4, 'HDL = 5.4 (LDL 333)')
,(5, NULL)
,(6, 'LDL: 132, Trigs=140')
,(7, 'His LDL one year ago was 120')
,(8, 'HDL 30 LDL 3210')
SELECT
SubjectID
,LEFT(SUBSTRING(SUBSTRING([TextResult], PATINDEX('%LDL%', [TextResult]), 8000), PATINDEX('%[0-9.-]%', SUBSTRING([TextResult], PATINDEX('%LDL%', [TextResult]), 8000)), 8000), PATINDEX('%[^0-9.-]%', SUBSTRING([TextResult], PATINDEX('%[0-9.-]%', [TextResult]), 8000) + 'X') -1) AS [LDL Text Value]
--,CAST(LEFT(SUBSTRING(SUBSTRING([TextResult], PATINDEX('%LDL%', [TextResult]), 8000), PATINDEX('%[0-9.-]%', SUBSTRING([TextResult], PATINDEX('%LDL%', [TextResult]), 8000)), 8000) + 'X', PATINDEX('%[^0-9.-]%', SUBSTRING([TextResult], PATINDEX('%[0-9.-]%', [TextResult]), 8000) + 'X') -1) AS float) AS [LDL Numeric Value]
FROM #demo
Thank you in advance.
You don't know what you don't know...