Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql stored procedure Like Operator variable

print("select CustomerNo, CustomerName, Address, City, State, Zip,
    Phone, Fax, ContactName, Email  
    from Customers where CustomerName like '%field%'");

Hi all. This is a simple question but I wasn't able to figure since I'm pretty new to tsql and sql in general.

I use the above stored procedure to do search. My question is for '%field%'. What variable do you use or how does it work in tsql? for example, "where Customers = @CustomerNo". how about for wildcard? how do you pass in a variable along with wildcard? I guess i can do "%" + "field" + "%" in the code but is there a way not to do that?

like image 605
Jack Avatar asked Dec 22 '08 22:12

Jack


People also ask

How LIKE operator works in SQL?

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.

How can we write like operator in stored procedure?

The value of the parameter is used along with LIKE operator (statement) in a SELECT statement. In the above Stored Procedure, the LIKE operator (statement) works as CONTAINS where it looks for the match throughout the string value. You can also use it as STARTS WITH and ENDS WITH options as shown below.

How use LIKE operator in SQL for multiple values?

The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator. The percentage(%) sign represents zero, one or multiple characters. The underscore(_) represents a single number or character.

Can we use SELECT statement in stored procedure?

We can not directly use stored procedures in a SELECT statement.


1 Answers

Wildcards are simply part of a string literal, e.g. '%field%' is just a string.

You can concatenate the wildcards onto your string and then use the string:

@Pattern = '%' + @CustomerName + '%';

...WHERE CustomerName LIKE @Pattern

Or else you can write an expression in the SQL involving concatenation:

WHERE CustomerName LIKE '%' + @CustomerName + '%'

There's no other magic solution for this.

like image 188
Bill Karwin Avatar answered Sep 28 '22 07:09

Bill Karwin