select rows that contain non alphanumeric - sql

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]%'

Related

How to check if a string contains exactly two words in an SQL query?

I need to execute a simple SQL query that will only select those names that are made up of exactly two words
SELECT NAME
FROM GROUP
WHERE NAME <Contains exactly two words>
You can use like and not like:
where name like '% %' and not like '% % %'
Another option is using LEN() (of course, I assume there are no trailing spaces):
SELECT [NAME]
FROM [GROUP]
WHERE LEN([NAME]) - LEN(REPLACE([NAME], ' ', '')) = 1
If the data in the NAME column has trailing space, you may use TRIM (for SQL Server 2017+) or a combination of LTRIM() and RTRIM() for earlier versions:
SELECT [NAME]
FROM [GROUP]
WHERE LEN(TRIM([NAME])) - LEN(REPLACE(TRIM([NAME]), ' ', '')) = 1
If you want both words present and exact:
SELECT *
FROM table
WHERE column LIKE '%word1%'
AND column LIKE '%word2%'

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 to select the column names of a table where column data contains '%' in the values?

How to select the column names of a table where column data contains '%' in the values?
Eg: In the table COMP there are two columns(Addr, Comp_Name) which has data containing '%' in its string. So my query should return those column_names(Addr, Comp_Name)
I dont get you right but i thing this will help you
You can use the escape identifier
--Queries
-- for %
select * from test_a where col1 like '%\%%' escape '\';
--for _
select * from test_a where col1 like '%\_%' escape '\';

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

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?

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