简体   繁体   中英

Using Regex in a SQL Select

I have a SQL column that contains JSON payloads. I'm writing a SQL query that will extract part of that column w/ regex.

In the following field:

{
   "myContent":{
      "fieldG":null,
      "valuable":"this is the text",
      "fieldH":[
         "a4a6ba1c2e0e4a9c89dac46f1092b505"
      ],
      "fieldI":"1"
   },
   "fieldJ":"1441375349399"
}

I want to scrape the string immediately after "valuable":

I was experimenting w/ something like this:

\"valuable\":\".*\"

... but that doesn't help. For starters, I only want what's AFTER valuable and colon. Also, that particular regex matches from "valuable:" all the way through the entire end of the line. That's way more text than I need.

In SQL Server 2016 CTP3 you could use JSON_VALUE function, eg: SELECT JSON_VALUE(column, '$.mycontent.valuable'). See http://blogs.msdn.com/b/jocapc/archive/2015/05/16/json-support-in-sql-server-2016.aspx

If you cannot wait for Sql Server 2016, you can use some JSON CLR library eg http://www.codeproject.com/Articles/1000953/JSON-for-SQL-Server-Part Otherwise yo would need to use PATINDEX and substring.

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