Using Regex in a SQL Select - sql

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, e.g.:
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 e.g. http://www.codeproject.com/Articles/1000953/JSON-for-SQL-Server-Part
Otherwise yo would need to use PATINDEX and substring.

Related

Querying full and sub-strings via multi-valued parameter using SQL

I am building a report with Microsoft SSRS (2012) having a multi-value parameter #parCode for the user to filter for certain codes. This works perfectly fine. Generally, my query looks like this:
SELECT ...
FROM ...
WHERE
TblCode.Code IN (#Code)
ORDER BY...
The codes are of following type (just an excerpt):
C73.0
C73.1
...
C79.0
C79.1
C79.2
Now, in additon to filtering for multiple of these codes I would like to als be able to filter for sub-strings of the codes. Meaning, when the user enters (Example 1)
C79
for #parCodes The output should be
C79.0
C79.1
C79.2
So eventually the user should be able to enter (Example 2)
C73.0
C79
for #parCodes and the output would be
C73.0
C79.0
C79.1
C79.2
I managed to implement both functionalities seperately, so either filtering for multiple "complete" codes or filterting for sub-string of code, but not both simultaneously.
I tried to do something like
...
WHERE
TblCode.Code IN (#parCode +'%')
ORDER BY...
but this screws up the Example 2. On the other hand, if I try to work with LIKE or = instead of IN statement, then I won't be able to make the parameter multi-valued.
Does anyone have an idea how to realize such functionality or whether IN statement pared with multi-valued parameters simply doesn't allow for it?
Thank you very much!
Assuming you are using SQL server
WHERE (
TblCode.Code IN (#parCode)
OR
CASE
WHEN CHARINDEX('.', Code)>0 THEN LEFT(TblCode.Code, CHARINDEX('.', TblCode.Code)-1)
ELSE TblCode.Code
END IN (#parCode)
)
The first clause makes exact match so for your example matches C73.0
The second clause matches characters before the dot character so it would get values C79.0, C79.1, C79.2 etc
Warning: Filtering using expressions would invalidate the use of an index on TblCode.Code

Use unaccent postgres extension in Knex.js Querys

I need make a query for a postgresdb without identify accents (á, í,ö, etc).
I'm already use Knex.js as query builder, and postgresql have a unaccent extension that works fine in sql querys directly to db, but in my code i use knex and unaccent function throws error in querys.
Can anyone help me, ¿is possible make querys with knex.js that use unaccent function of postgresql?
My solution is to process the string before submitting the query using the following code:
const normalize = (str) => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
console.log(normalize('Ấ Á Ắ Ạ Ê')) -> 'A A A A A'.
Or if you use postgresql version 13 or later it already supports that functionality.
select normalize('hồ, phố, ầ', NFC) → 'ho, pho, a' -- NFC (the default), NFD, NFKC, or NFKD.
Document: https://www.postgresql.org/docs/13/functions-string.html

How to set a substring from a sql statement through Groovy setter

I am reading a sql table through a Sql statement, meanwhile i am also using a substring. Since the Substring is like virtual i am not writing in the database. How am i able to set this read substring using a setter in groovy using sql.eachrow.
I have tried setFinishingTime(row.FinishingTime)
This is in my groovy code.
sql.eachRow('select * from [Database].[dbo].[table] order by FinishingTime')
{ row ->
---
machine.setFinishingTime(row.FinishingTime)
}
In sql query i have a code.
substring([FinishingTime], charindex(' ', [FinishingTime]) + 1, len([FinishingTime])).
I want to set in FinishingTime the substring of the column finishingtime. How can i achieve that, It works in sql management studio but how do i use the same in groovy through sql.eachRow.

postgresql replace function using pattern matching characters

I am having a table named "OptionsDetail" with column named "URL" in postgresql database. The "URL" column contain the following data
URL
http://www.site1.com/ebw/file1/detail.action?cid=1
http://www.another2.com/ebw/file1/detail.action?cid=11&code=MYCODE
http://www.anothersite3.com/ebw/file1/detail.action?cid=12&code=ANOTHERCODE&option=ROOM
Now I want to replace the data in URL to
URL
/file1/detail.action?cid=1
/file1/detail.action?cid=11&code=MYCODE
/file1/detail.action?cid=12&code=ANOTHERCODE&menu=ROOM
I wrote the following query to perform the above functionality
UPDATE "OptionsDetail" SET "URL" = replace("URL",'http://%/ebw/file1','/file1') WHERE "URL" LIKE '%/ebw/file1%';
And also another way I wrote like this
UPDATE "OptionsDetail" SET "URL" = replace("URL",'%/ebw/file1','/file1') WHERE "URL" LIKE '%/ebw/file1%';
Query is executing successfully saying like for ex: 200 rows affected but "URL" column data is not changing the way I need, the data is remaining as it is.
Please help me to resolve this issue
The problem is that replace doesn't support wildcards like %:
replace("URL",'http://%/ebw/file1','/file1')
^^^
You can use regexp_replace instead:
UPDATE YourTable
SET URL = regexp_replace(URL, 'http://.*/ebw/file1', '/file1')
WHERE URL LIKE '%/ebw/file1%'
Note that regexp_replace uses different wildcards than like. In regular expressions, "Any number of any character" is .* instead of %.
See it working at SQL Fiddle.

RegEx in SQL - How to Change the values of a column in SQL Server Database

I am trying to change the values of a column in my SQL Server Database.
Table: crm.activity
Column: Content
The values look like this:
value 1:
{\rtf1\ansi\ansicpg1252\deff0\deflang2055{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\f0\fs17 Appointment made\par
}
value 2:
{\rtf1\ansi\ansicpg1252\deff0\deflang2055{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\f0\fs17 Ask for offer\par
}
What I need is just the bold text.
Is it possible like using RegEx to go through all the columns and change the value???
To my knowledge, you can't do regex replaces in MySQL out of the box. However, if there's only one bold string per column, it should be easy enough to do the trick with string functions like LOCATE and SUBSTR.
http://dev.mysql.com/doc/refman/5.7/en/string-functions.html
Here you go. This is for MySQL:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('{\rtf1\ansi\ansicpg1252\deff0\deflang2055{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}} \viewkind4\uc1\pard\f0\fs17 **Appointment made**\par}', '**', -2), '**', 1);
# => Appointment made
Or to update (try it first and make sure you have a backup):
UPDATE mytable SET mycolumn = SUBSTRING_INDEX(SUBSTRING_INDEX(mycolumn, '**', -2), '**', 1);
If its SQL Server, do a bit of googling (mssql update replace regex) on how to add a regex replace method to SQL server. The regex you will need is: .+\\fs\d+\s(.+)\\par\s?}, replace this with $1. As a fallback solution (not sure how much data you have in that table) you could write a small script that selects all records, replaces the string, and updates the database.