Substring sql nvarchar value from start to first non-int character
-
01-07-2021 - |
Question
Have a numeric nvarchar values with some "extra-symbols" For example 1/2, 9/6, 14A They allways starts with number.
How can I substring this "extra-symbols" values from start to index of first non-int character? The example line must be 1, 9, 14
Something like
SUBSTRING(Value, 0, CHARINDEX(Value, /*Here must be all symbols except numbers*/))
Solution
Please try the query:
SELECT LEFT(ColumnName,PATINDEX('%[^0-9]%', ColumnName+'a')-1) FROM TABLE
OTHER TIPS
Try this:
SELECT CASE PATINDEX('%[^0-9]%', ColumnName) WHEN 0 THEN ColumnName
ELSE LEFT(ColumnName,PATINDEX('%[^0-9]%', ColumnName)-1) END
Another option that avoids appending a character to every row in the table:
SELECT SUBSTRING(col, 1, COALESCE(NULLIF(PATINDEX('%[^0-9]%', col)-1, -1), 255))
FROM dbo.mytable;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow