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.
Related
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 '\'
);
I am trying to use CASE WHEN right after CTE definition but the query expects SELECT only:
WITH A AS
(...) --long query here
CASE WHEN #parameter = '' THEN
SELECT * FROM A
ELSE
SELECT * FROM A WHERE field like '%' + #parameter + '%'
END
Is there a way to make this query work, besides using OR statement?
First of all, you are using CASE WHEN wrong. It is supposed to be used to return a single value, not a table, as part of for example a select clause. It is not intended to be used as flow control to run one of two queries. Use IF for that.
Second, you cannot split a CTE from a select, it is part of the same statement. You can't go "Here is a CTE, now run one of two statements from it", that is not how CTE statements are written. You can reuse a CTE multiple times in a select, but is going to run the whole select, not just part of it.
Some alternate ways that can work
You can use an IF around the whole query, and write it out twice. This way only one version of the query actually runs.
IF #parameter = ''
SELECT (your query here)
ELSE
SELECT (your query here) WHERE field like ...
You could use dynamic SQL, build the first part of the query as a string. Then only add on the where clause if needed, then run the resulting SQL.
You can use OR in the WHERE clause:
WITH A AS
(...) --long query here
SELECT *
FROM A
WHERE (field like '%' + #parameter + '%') OR #parameter = '';
If field is never NULL, then this is equivalent to:
WITH A AS
(...) --long query here
SELECT *
FROM A
WHERE field like '%' + #parameter + '%';
(LIKE '%%' matches any non-empty string.)
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?
I have a situation where I need to use a select statement in a where but then also append and prepend wildcards to the value it returns. E.g something like:
select * from [Customers.customervisibility] where userId like '%,' (Select Id from [Users.Users] where name ='MyName') ',%'
but running this gives:
Incorrect syntax near ',%'.
Now the Select Statement is only ever going to return 1 id, so I don't know if there is a better way to write it maybe using a function.
The overall goal is so that I can select the rows from [customer.customervisibility] where the id is contained in a comma seperated string column [UserId]
e.g. if id = 8
I need to get the rows where *,8,*...
It has to be inline, I cannot use variable, and you will have to excuse the TERRIBLE database design. this is so that it will work with third party software
Try this where clause
If your DBMS support Concat the use this.
userId like concat('%' ,(Select top 1 cast(Id as varchar(50)) from [Users.Users] where name ='MyName') ,'%')
Else
userId like '%' +(Select top 1 cast(Id as varchar(50)) from [Users.Users] where name ='MyName') +'%'
I have used Top 1 to avoid sub-query returns more than one row error if in case your subquery returns more than one row
You seem to have forgotten the concatenation character + for strings. Try below query:
select * from [Customers.customervisibility] where userId like '%,'+(Select Id from [Users.Users] where name ='MyName')+',%'
This will give results whose userId contains your Id where userId is a comma separated string.
SELECT *
FROM [Customers.customervisibility]
WHERE (userId LIKE '% , Select Id from [Users.Users] where status="MyName" %')
Try this:
select * from [Customers.customervisibility] where convert(VARCHAR(100),userId) like '%'+(Select Id from [Users.Users] where name ='MyName')+'%'
I'm not sure how to go about this:
I have a column named description in my database. I have a list of keywords. I want to select the rows where the description contains at least one of the strings in my list.
The list is of strings, and the description is of type TEXT.
I just don't want to do a hideous brute force method of doing multiple LIKEs (because my list is currently 50 elements).
I think you can use a SQL query like this (just I write it on the fly):
WITH tags(tag) AS (
SELECT * FROM (VALUES ('tag1'),('tag2'),('tag3'),('tag4')) AS tags(tag))
SELECT DISTINCT description
FROM tbl
WHERE (description LIKE '%' || tag || '%');
That you can insert your list instead of ('tag1'),('tag2'),('tag3'),('tag4'). That you need something like "(" + replace(yorTagString, ",", "),(") + ")".
[SQL Fiddle Demo]