Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL. Why does this 'Like' statement with a wildcard not work?

Declare @Temp1 as nvarchar(max) = '[10004120][1100][10033583][1005]'
Declare @Temp2 as nvarchar(max) = '[10004120][1100]'

If @Temp1 like @Temp2 + '%'
    Print 'Yup'

Why does this not work? I don't get the "yup" message.

like image 869
Stephanus DJ Avatar asked Jul 19 '18 18:07

Stephanus DJ


People also ask

What is the wildcard character in SQL LIKE statement?

The SQL LIKE Operator The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Can you use wildcard in SQL in statement?

You can use the % and _ wildcards with the SQL LIKE statement to compare values from a SQL table. Here is the basic syntax for the SQL Like statement. The % matches zero, one or more characters while the _ matches a single character.

What are the two wildcard characters used with the like clause?

There are two wildcards used in conjunction with the LIKE operator. The percent sign represents zero, one, or multiple characters. The underscore represents a single number or character. These symbols can be used in combinations.


2 Answers

This doesn't work because the brackets in the string have a special function in a LIKE statement - items between the brackets constitute a set of values that the singular character at the specified position matches. Your original pattern looks for a 1,0,4, or 2 followed by a 1 or an 0. To make this work, you should have a pattern like this:

Declare @Temp2 as nvarchar(max) = '[[]10004120][[]1100]'
like image 195
Laughing Vergil Avatar answered Sep 30 '22 16:09

Laughing Vergil


You have the like backwards. The pattern is the second operand. The logic should be:

 @temp1 like @temp2 + '%'
like image 30
Gordon Linoff Avatar answered Sep 30 '22 15:09

Gordon Linoff