I have a column in SQL Server that has a string that looks like this. I’m trying to get the value of the “some_id” which in this case would ‘12345678911’. Any help on how I could get just that numerical value.
I can’t seem to get it using the Substring()
and Charindex()
functions.
"""some_id""=>""12345678911"", ""someother_id""=>"""", ""somethingelse""=>""False"", ""anotherString""=>""0"" -- trying to get 12345678911 without the quotes.
Any help would be much appreciated.
EDIT – Heres where my attempt is currently at, and I also did not want that 28 characters hard coded. It should stop at the first double quote.
select TOP 100 SUBSTRING(col,CHARINDEX('some_id',col), 28) From tableName -- RESULT -- some_id""=>""12345678911"
Advertisement
Answer
For your given example the following returns the required result. You just create a substring from your starting point and then find the next pair of double quotes, then substring between the starting point and the next pair of double quotes:
DECLARE @Col NVARCHAR(MAX) = '"""some_id""=>""12345678911"", ""someother_id""=>"""", ""somethingelse""=>""False"", ""anotherString""=>""0""', @PatternToFind NVARCHAR(32) = 'some_id""=>""'; SELECT SUBSTRING(RemainingString, 1, CHARINDEX('""',RemainingString)-1) FROM ( SELECT SUBSTRING(Col,StartIndex+LEN(@PatternToFind),LEN(Col)) RemainingString FROM ( SELECT CHARINDEX(@PatternToFind,@col) StartIndex , @Col Col -- Comment out this line and uncomment the next 2 to use a table -- , MyCol Col --FROM myTable ) A ) B
Which can be combined into a single statement, but you can see that duplicates code, so I find separating it out is clearer:
SELECT SUBSTRING(SUBSTRING(Col,CHARINDEX(@PatternToFind,col)+LEN(@PatternToFind),LEN(Col)), 1, CHARINDEX('""',SUBSTRING(Col,CHARINDEX(@PatternToFind,Col)+13,LENn(Col)))-1) FROM ( SELECT @Col Col -- Comment out this line and uncomment the next 2 to use a table -- , MyCol Col --FROM myTable ) A