Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL server use "IF variable LIKE pattern"

Tags:

sql-server

Why this doesn't work?

DECLARE @str varchar = '######'

IF @str LIKE '%###%' SELECT 1

but this works

IF '######' LIKE '%###%' SELECT 1

UPDATE

why this works

DECLARE @Comment varchar(255) = '[A-B-C-D]'

IF @Comment LIKE '%[%-%-%-%]%' SELECT 1

however this doesn't work?

DECLARE @Comment nvarchar(255) = '[A-B-C-D]'

IF @Comment LIKE '%[%-%-%-%]%' SELECT 1
like image 490
Fallflame Avatar asked Aug 27 '15 13:08

Fallflame


People also ask

Can we use variable with like operator in SQL?

Using the CONCAT() function, we can work with user variables in LIKE clause. The syntax is as follows.

How do you search for a specific pattern in a column in SQL?

LIKE clause is used to perform the pattern matching task in SQL. A WHERE clause is generally preceded by a LIKE clause in an SQL query. LIKE clause searches for a match between the patterns in a query with the pattern in the values present in an SQL table.

What is like and not like in SQL?

The SQL LIKE and NOT LIKE operators are used to find matches between a string and a given pattern. They are part of standard SQL and work across all database types, making it essential knowledge for all SQL users.


1 Answers

Add to your variable type length.

DECLARE @str varchar = '######'

IF @str LIKE '%###%' SELECT 1

is the same as (implicit cast will change it to '#')

DECLARE @str varchar(1) = '######'

/* IF '#' LIKE '%###%' SELECT 1 */
IF @str LIKE '%###%' SELECT 1

This will work:

DECLARE @str varchar(20) = '######'

IF @str LIKE '%###%' SELECT 1
like image 169
Lukasz Szozda Avatar answered Nov 06 '22 00:11

Lukasz Szozda