简体   繁体   中英

How to extract a string between two characters

Situation:

I have a column decoded from Hex to varchar where values look like this:

{"something":"example"}

Objective:

I would like to extract the second word between the quotes.

What i tried:

I started with a couple of substring and charindex functions but my code looks more complicated than it should be.

SELECT SUBSTRING(
            SUBSTRING(
                '{"something":"example"}',
                charindex(':"','{"something":"example"}')+2,
                LEN('{"something":"example"}')-charindex(':"','{"something":"example"}')+2),
            0,
            CHARINDEX('"',SUBSTRING(
                '{"something":"example"}',
                charindex(':"','{"something":"example"}')+2,
                LEN('{"something":"example"}')-charindex(':"','{"something":"example"}')+2))
                )

Any ideas?

If you're on SQL Server 2016+, you can use OPENJSON :

SELECT [value]
FROM OPENJSON('{"something":"example"}');

db<>fiddle

So against a table:

SELECT [value]
FROM (VALUES('{"something":"example"}'),
            ('{"another":"sample"}'))V(S)
     CROSS APPLY OPENJSON(V.S);

This returns:

value
-------
example
sample

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM