I'm in the process of converting a CLR function that utilizes regex to a SQL function. I know that SQL Server does not fully support regex, but i just need one case to work which is a word search.
Search Field Value: {"Id":1234, "Title": "The quick brown"}
Regex Pattern in .NET: '\\b' + '"Id":1234' '\\b'
I want to be able to match when Search field contains "Id":1234 but not "Id":12345
How do I achieve this? I've tried this but obviously doesn't work when the number 1234 ends with space or b instead of comma.
DECLARE @match bit = 0
DECLARE @input nvarchar(max) = '{"Id":1234, "Title": "The quick brown"}'
DECLARE @pattern nvarchar(max) ='"Id":1234'
SELECT @match = 1 FROM (VALUES ('')) table1 (column1)
WHERE @Input LIKE '%' + @pattern + ',%'
Considering you have JSON data, why not parse it as such?
DECLARE @JSON nvarchar(MAX) = '{"Id":1234, "Title": "The quick brown"}';
SELECT *
FROM (VALUES(@JSON)) V(J)
CROSS APPLY OPENJSON(@JSON)
WITH (Id int,
Title varchar(50)) OJ
WHERE OJ.Id = 1234;
In general, parsing JSON content with regex alone is not ideal. We might be able to use SQL Server's enhanced LIKE
operator here:
SELECT *
FROM yourTable
WHERE json LIKE '%"Id":1234[^5]%';
This would return all occurrences of "Id":1234
which are followed by any character other than 5. Note that there should always be at least one character after a match, since the key value pair needs to be closed in the JSON.
I think pattern '%"Id":1234[^a-zA-Z0-9]%'
will do.
It uses negated character class [^a-zA-Z0-9]
, which works as in regular regex :)
Sample:
declare @tbl table (col varchar(100));
insert into @tbl values
('{"Id":1234, "Title": "The quick brown"}'),
('{"Id":1234, "Title": "The quick brown"}'),
('Id":1234, "Title": "The quick brown"}'),
('{"Id":12345, "Title": "The quick brown"}');
select *
from @tbl
where col like '%"Id":1234[^a-zA-Z0-9]%'
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.