I believe [ and ] are special characters when using with LIKE clause in TSQL( SQlserver 2005 if it matters). How do i escape the search term in the stored procedure, i did below but does not return valid records even while exists
SELECT * FROM Table WHERE Column LIKE '%['+ #searchedTerm +']'
So which is the valid thing to do, when searching like above??
You need to escape the opening (not the closing) bracket like this:
LIKE '%[[]' + #searchedTerm + ']'
The MSDN page for LIKE has a section "Using Wildcard Characters As Literals"
Edit, after comment
LIKE '[[]cap]%' searches for a name containing the string [cap]
LIKE '[wel]%' searches for a name containing one of the letters w, e or l
Try this:
DECLARE #searchedTerm as varchar(50);
SET #searchedTerm = 'TEST VALUE'
SELECT * FROM Table WHERE Column LIKE '%[[]' + #searchedTerm +']'
try this:
SELECT * FROM Table WHERE Column LIKE '%/['+ #searchedTerm +']' {escape '/'}
Related
Why these SQLs can't work in PostgreSQL?
SELECT * FROM (t as a);
or
SELECT * FROM (t);
ERROR: syntax error at or near ")"
Those SQLs work well in MySQL.
Well, it's invalid SQL.
If you want to give the table an alias you need to use from t as a.
The form from (....) requires a valid query inside the parentheses and t as a (or just t) is not a valid query. Additionally: a derived table (which is what (...) defines) requires an alias. So at least it has to be from (...) as bla
To get all rows and all columns from a table the SQL standard provides the shortcut table some_table which is supported by Postgres.
So the following would be valid:
select * from (table t) as a
Typically, table alias' are applied where there is a join. For example:
SELECT alias1.login_name, alias2.name
FROM tablename1 AS alias1
JOIN tablename2 AS alias2
ON alias1.id = alias2.role_id;
To apply an alias to a single table:
SELECT * FROM tablename AS alias;
..will do it for you, no need for parentheses.
You can confirm/test by example below if value is an integer:
SELECT * FROM tablename AS alias
WHERE alias.colum = value;
..or if value is a string:
SELECT * FROM tablename AS alias
WHERE alias.colum = 'value';
postgreSQL is strongly-typed, so the first example above will work for Int and Bool values, however if you have Date or other values, you may need to apply type casting. See this link for helpful info*: www.postgresqltutorial.com/postgresql-tutorial/postgresql-cast.
**Remember: For psql strings, always use single quotes for values, use double quotes for table names and column names.
Need help with postsql query field matching a certain domain names in the end as per below in a particular FIELD.
1234.abc.xyz.com;
0971.abc.xyz.com
WHERE CAST (domain_name AS text) LIKE '%\d{4}.abc.xyz.com%'
#where domain_name is the FIELD name
~ is used for regular expression matching, LIKE for simple matching. Read more about them here: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-SIMILARTO-REGEXP
If you just want to find domain_name that end in a particular text, the simple matching works fine (don't know if you really need the cast):
select * from tbl_test where domain_name LIKE '%.abc.xyz.com'
This will not work correctly:
select * from tbl_test where domain_name ~ '\d\d\d\d.abc.xyz.com'
The dot (.) is "any character" in a regular expression so this domain would be selected: abcd.abcxxyzdcom. You need to escape the dot in the string for it to be treated literally like this: '\d\d\d\d\.abc\.xyz\.com'
Underscore is a wildcard for "any character" in the simple LIKE.
use ~ followed by your search pattern as regular expression:
where domain_name ~ '\d\d\d\d\.abc\.xyz\.com'
playground:
https://dbfiddle.uk/O0Q_Ctmo
create table tbl_test (
domain_name varchar
);
insert into tbl_test VALUES
('1234.abc.xyz.com'),
('0971.abc.xyz.com'),
('0971.abc.xyz.bam'),
('1234.xxx.xyz.com'),
('123.xxx.xyz.com'),
('aaaa.xxx.xyz.com')
CREATE TABLE
INSERT 0 6
select * from tbl_test
where domain_name ~ '\d\d\d\d\.abc\.xyz\.com'
domain_name
1234.abc.xyz.com
0971.abc.xyz.com
SELECT 2
fiddle
I have a users table with first name and last name. I want to find a user for a string like 'clark kent'.
I do this
SELECT * FROM user WHERE fisrt_name || ' ' || last_name LIKE '%clark kent%'
but I don't have any result.
Why? If I search for 'clark' or 'kent' it works.
Solution:
SELECT *
FROM user
WHERE TRIM("first_name") || ' ' || TRIM("last_name") LIKE '%clark kent%';
Per the OP's comments, the difficulty was that first_name and last_name were CHAR and not VARCHAR fields, meaning that the fields are space-padded to their length. That is, the string 'clark' stored as CHAR(8) is 'clark[sp][sp][sp]'.
When concatenating the fields together to form a "full name", then, the resulting string had unexpected spaces: 'clark[sp][sp][sp][sp]kent[sp][sp][sp][sp]'.
(As an aside, in strict SQL, CHAR columns are rather counter-intuitive. They compare without regard to space padding, but the LIKE operator does not ignore space padding. See the Firebird FAQ.)
Try
SELECT *
FROM user
WHERE upper(fisrt_name) LIKE '%CLARK%'
and upper(last_name) LIKE '%KENT%'
I want to search a column and get values where value containts \ .
I tried select * from "Values" where "ValueName" like '\'. But returns no value.
Also tried like "\" and like'\''%' etc. But no results.
See the DB2 Documentation on the LIKE predicate, in particular the parts about escape expressions.
What you want is
select * from Values where ValueName like '\\%' escape '\'
To give an example of usage:
create table backslash_escape_test
(
backslash_escape_test_column varchar(20)
);
insert into backslash_escape_test(backslash_escape_test_column)
values ('foo\');
insert into backslash_escape_test(backslash_escape_test_column)
values ('no slashes here');
insert into backslash_escape_test(backslash_escape_test_column)
values ('foo\bar');
insert into backslash_escape_test(backslash_escape_test_column)
values ('\bar');
select count(*) from backslash_escape_test where
backslash_escape_test_column like '%\\%' escape '\';
returns 3 (all 3 rows with \ in them).
select count(*) from backslash_escape_test where
backslash_escape_test_column like '\\%' escape '\';
returns 1 (the \bar row).
select * from Values where ValueName like '%\\%'
values is a not so good name because it may be confused with the values keyword
Don't escape it. You just need wildcards around it like this:
select count(*)
from escape_test
where test_column like '%\%'
But, suppose you really do need to escape the slash. Here's a simpler, more straightforward answer:
The escape-expression allows you to specify whatever character for escaping that you wish. So why use a character that you're looking for, thus requiring you to escape it? Use any other character instead. I'll use a plus sign as an example, but it could be a backslash, pound-sign, question-mark, anything other than a character you are looking for or one of the wildcard characters (% or _).
select count(*)
from escape_test
where test_column like '%\%' escape '+';
Now you don't have to add anything into your like-pattern.
To hold myself to the same standard of proof that #Michael demonstrated --
create table escape_test
( test_column varchar(20) );
insert into escape_test
(test_column)
values ('foo\'),
('no slashes here'),
('foo\bar'),
('\bar');
select 'test1' trial, count(*) result
from escape_test
where test_column like '%\%'
UNION
select 'test2', count(*)
from escape_test
where test_column like '%\\%' escape '\'
UNION
select 'test3', count(*)
from escape_test
where test_column like '%\%' escape '+'
;
Which returns the same number of rows for each method:
TRIAL RESULT
----- ------
test1 3
test2 3
test3 3
I am building a SQL sting, mostly the WHERE clause, on the fly based on parameters passed in and the executing the built string. So in the end it is: EXEC (#strSELECT + #strFROM + #strWHERE + #strORDERBY).
My #strSELECT looks like: SET #strSELECT = 'SELECT DISTINCT FieldA, FIELDB, FIELDC'
This all works so far, but now I added a nested function field to the end of #strSELECT so the whole #strSELECT now looks like: SET #strSELECT = 'SELECT DISTINCT FieldA, FIELDB, FIELDC, UPPER(REPLACE(CONVERT(VARCHAR, CAST(MyStringDateField AS DATETIME),6),' ','-')) AS FormattedDate'
I know the new nested function field works because I tested it without concantenation and I also know that the problem is with the single quotes [' ','-'] within the function. Can anyone help me with the correct quote syntax when building the query string? thnx.
You'll have to make your nested function look like this:
UPPER(REPLACE(CONVERT(varchar, CAST(MyStringDateField AS datetime),6),'' '',''-''))
Double up on the quotes inside the string. This works for me and returns "02-MAR-11":
DECLARE #strSELECT nvarchar(200)
SET #strSELECT = 'SELECT UPPER(REPLACE(CONVERT(VARCHAR, CAST(GETDATE() AS DATETIME),6),'' '',''-'')) AS FormattedDate'
EXECUTE sp_executesql #strSELECT
To insert a single quote in a T-SQL string you prepend another single quote. Thus your #strSelect statement becomes
SET #strSELECT = 'SELECT DISTINCT FieldA, FIELDB, FIELDC, UPPER(REPLACE(CONVERT(VARCHAR, CAST(MyStringDateField AS DATETIME),6),'' '',''-'')) AS FormattedDate'
That doesn't mean that this is the right way to do it though. You should try to use parameterized queries wherever possible to avoid sql injection attacks