How do i match text excluding difference between brackets in SQL server? - sql

I've an audit log table that has a series of strings like
"Some Text[details]more text"
the pattern before and after the [details] indicates what the audit trail entry type is. The text in the bracket indicates what it is for. I want to create a query to only find the audit entries i'm after. I thought to use the following like "Some Text[%]more text" but it does not seem to work
When I run the below query it retrieves the expected results + more
select top 1000 *
from Table
where NAME like 'Some Text%'
When I try
select top 1000 *
from Table
where NAME like 'Some Text[%'
Nothing comes back is the

Brackets have a special syntactic meaning in regular expressions. So you need to escape the bracket if you want to use it in your query:
select top 1000 *
from Table
where NAME like 'Some Text[[]%'
Special characters can be escaped by placing them inside brackets. In this case, the opening bracket itself needs to be placed inside brackets, i.e. [[]

try the t-sql code below:
create table dbo.tblTest (ID int IDENTITY(1, 1), strings varchar(200))
insert dbo.tblTest
select 'i have to find this text excluding [these strings inside the brackets]'
union all select '[don''t include these texts inside the brackets]. but include these!'
union all select 'why can''t i search for these, but [not these]? nothing seems to work when brackets are involved. :('
select *
from dbo.tblTest
DECLARE #stringToSearchFor VARCHAR(200) = 'nothing seems'
SELECT t.*
FROM dbo.tblTest t
JOIN
(SELECT nobrackets.*
FROM
(SELECT cleanString = REPLACE(t.strings, SUBSTRING(t.strings, CHARINDEX('[', t.strings), CHARINDEX(']', t.strings) - CHARINDEX('[', t.strings) + 1), '')
, t.ID
FROM dbo.tblTest t) noBrackets
WHERE noBrackets.cleanString LIKE CONCAT('%', #stringToSearchFor, '%')) tNoBracket ON tNoBracket.ID = t.ID

If you will take sometime here in stackoverflow, a lot of post will answer your question.. Please see below.
You need to use [ ] bracket to surround the text with special character..
The query now look something like:
select top 1000 *
from Table
where NAME like '[Some Text[]%'
SQL LIKE CONDITION
SQL Server LIKE containing bracket characters

select top 1000 *
from Table
where NAME like 'Some Text[[%] more text'
or
select top 1000 *
from Table
where NAME like 'Some Text![%] more text' ESCAPE '!'
How can I escape square brackets in a LIKE clause?

Related

select rows that contain non alphanumeric

I need to select the rows that contain non alphanumeric values in names. I got part of the solution, but, I am also getting rows with spaces, hyphens and single quotes. So, I need to pull the rows with that are alphanumeric and also not pull rows with space and - and '.
Did some research online
select *
from EMP
where NAME like '%[^a-z,1-9]%'
I don't want to get rows with - or spaces or '
Here is a way using number table to find bad chars:
create table #GoodLetters(letter char(1))
insert into #GoodLetters
values
('a'),('b'),('c'),('d'),('e'),('f'),('g'),('h'),('i'),('j'),('k'),('l'),('m'),('n'),('o'),('p'),('q'),('r'),('s'),('t'),('u'),('v'),('w'),('x'),('y'),('z')
,('0'),('1'),('2'),('3'),('4'),('5'),('6'),('7'),('8'),('9')
,('-'),(' '),('''')
--select * from #GoodLetters
select a._key, a.name,substring(a.name, v.number+1, 1)
from (select 'Your Key' _key,name from emp ) a
join master..spt_values v on v.number < len(a.name)
left join #GoodLetters GL on substring(a.name, v.number+1, 1)=GL.letter
where v.type = 'P'
and GL.letter is null
drop table #GoodLetters
I think it should go like that:
select *
from EMP
where (NAME NOT LIKE '%-%' OR NOT LIKE '%[ ]%' OR NOT LIKE '%\'%' ESCAPE '\');
'%[ ]%' --> gives you one or more spaces
ESCAPE --> requiered for special character
you can also add ' , - and space chars to the regex.
select *
from EMP
where NAME like '%[^a-z,1-9''- ]%'
Hyphen is a little tricky. Because it is used for character classes, it needs to be the first character in the class. So:
where name like '%[^- a-z,1-9]%'

DB2 efficient select query with like operator for many values (~200)

I have written the following query:
SELECT TBSPACE FROM SYSCAT.TABLES WHERE TYPE='T' AND (TABNAME LIKE '%_ABS_%' OR TABNAME LIKE '%_ACCT_%')
This gives me a certain amount of results. Now the problem is that I have multiple TABNAME to select using the LIKE operator (~200). Is there an efficient way to write the query for the 200 values without repeating the TABNAME LIKE part (because there are 200 such values which would result in a really huge query) ?
(If it helps, I have stored all required TABNAME values in a table TS to retrieve from)
If you are just looking for substrings, you could use LOCATE. E.g.
WITH SS(S) AS (
VALUES
('_ABS_')
, ('_ACCT_')
)
SELECT DISTINCT
TABNAME
FROM
SYSCAT.TABLES, SS
WHERE
TYPE='T'
AND LOCATE(S,TABNAME) > 0
or if your substrings are in table CREATE TABLE TS(S VARCHAR(64))
SELECT DISTINCT
TABNAME
FROM
SYSCAT.TABLES, TS
WHERE
TYPE='T'
AND LOCATE(S,TABNAME) > 0
You could try REGEXP_LIKE. E.g.
SELECT DISTINCT
TABNAME
FROM
SYSCAT.TABLES
WHERE
TYPE='T'
AND REGEXP_LIKE(TABNAME,'.*_((ABS)|(ACCT))_.*')
Just in case.
Note, that the '_' character has special meaning in a pattern-expression of the LIKE predicate:
The underscore character (_) represents any single character.
The percent sign (%) represents a string of zero or more characters.
Any other character represents itself.
So, if you really need to find _ABS_ substring, you should use something like below.
You get both rows in the result, if you use the commented out pattern instead, which may not be desired.
with
pattern (str) as (values
'%\_ABS\_%'
--'%_ABS_%'
)
, tables (tabname) as (values
'A*ABS*A'
, 'A_ABS_A'
)
select tabname
from tables t
where exists (
select 1
from pattern p
where t.tabname like p.str escape '\'
);

How do we match the special character(s) in sybase using like?

How do we match the special character(s) in sybase using like?
I'm using the like condition as a filter to any characters user inputted. Currently using the sybase database. I was able to retrieved some results by inputting some words, But if the user input some special characters like square bracket. It doesn't return any result but when I check the database I can see the square bracket or any special characters in the database.
Sample Data: column searchField : [IAN]Stackoverflow
Declare #value varchar(50)
SET #value = '[IAN]Stackoverflow'
SELECT * FROM Table1 WHERE searchField LIKE '%#value%
I think what you're asking would be solved by:
SELECT * FROM Table1 WHERE searchField LIKE '%' + #value + '%'
You can even have the variable part of the LIKE expression from a table, if you have more than one constant section in a list of values to compare:
SELECT t.*
FROM Table1 t, #surnames s
WHERE t.searchField LIKE '%' + s.surname + '%'
or something like that.

T-SQL Using CONTAINS predicate with Hyphen

Imagine a table (table1) with one column (column1) and one record whose value is 'roll-over'. Then use the following SQL query and you will not get any records.
select * from table1 where contains(column1, ' "roll-over" ')
Is there a way to escape the hyphen in the search text? So far I have not been successful trying this (I have tried all below escapes with no success).
select * from table1 where contains(column1, ' "roll\-over" ')
select * from table1 where contains(column1, ' "roll!-over" ')
select * from table1 where contains(column1, ' "roll[-]over" ')
Also, please note that using the LIKE keyword is not possible for my application because I am taking advantage of full-text search indexing.
It looks like you may not be able to do that. Give this article a read:
https://support.microsoft.com/en-us/help/200043/prb-dashes---ignored-in-search-with-sql-full-text-and-msidxs-queries
They suggest searching only alphanumeric values (lame) or using the LIKE Clause (not an option for you).
Partial solution: you can force the query to return records containing hyphens (or any character) by using the charindex function to test that the string contains the character, e.g.:
select * from table1 where contains(column1, ' "roll-over" ')
and charindex('-', column1) > 0

combine two CONTAINS calls within where clause

I'm trying to create the following SQL query (as in, this is an example of the final query) :-
DECLARE #SearchQuery AS NVARCHAR(100) = 'yellow bird'
SELECT Id, Name
FROM dbo.FooBars
WHERE CONTAINS(Name, N'FORMSOF(Thesaurus, yellow)')
AND CONTAINS(Name, N'FORMSOF(Thesaurus, bird)')
Notice how I've got two CONTAINS lines? This is because the search query has two words in it. (a space is the delimiter). This query could be from 1 to n words.
How can I generate this SQL code based upon the number of words in the search query?
You can put the "AND" in the contains itself, so it coud be
select *
from dbo.FooBars
where contains(Name, 'FORMSOF(Thesaurus, yellow) AND FORMSOF(Thesaurus, bird)')
with the string 'FORMSOF(Thesaurus, yellow) AND FORMSOF(Thesaurus, bird)'
built up into a variable like
declare #searchCriteria varchar(200)
set #searchCriteria = 'Some string you built up'
select *
from dbo.FooBars
where contains(Name, #searchCriteria)