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
Using the CONCAT() function, we can work with user variables in LIKE clause. The syntax is as follows.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With