views:

94

answers:

6

Hello everyone,

I am using SQL Server 2008 Enterprise on Windows Server 2008 Enterprise. In the stored procedure, I need to pass parameter to a select-where-like statement. For example,

@department is store procedure input parameter, its type is varchar(20),

select * from sometable where somecolumn LIKE '%@department%' 

but seems my statement above does not work, any ideas how to pass parameter @department to like statement?

thanks in advance, George

+6  A: 
select * /*But don't use * in production!*/
from sometable 
where somecolumn 
LIKE '%' + @department + '%' 
Martin Smith
Thanks, question answered!
George2
+4  A: 

You concatenate the strings:

select * from sometable where somecolumn LIKE '%' + @department + '%'
Guffa
+2  A: 

It's a variable, it goes outside the quotes.

select * from sometable where somecol like '%' + @department + '%'

Or, more preferably, add the %s to the variable and just use it directly

Donnie
+2  A: 

try:

select * from sometable where somecolumn LIKE '%' + @department + '%'
Scozzard
If you post code or XML, **please** highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it!
marc_s
+2  A: 

You could do something like this:

select * from sometable where somecolumn LIKE '%' + @department + '%'
Josh
@Josh - No it doesn't. This is not dynamic SQL
Martin Smith
You are correct sir. It was my knee jerk reaction for doing string concatenation in SQL. Still have nightmares about some of the code I have seen. I removed the statement from the answer.
Josh
@Josh - Good knee jerk reaction to have!
Martin Smith
A: 
select * from sometable 
where CHARINDEX(@department,somecolumn)>0 

You can also use the CHARINDEX function.

Talasila