Wednesday, March 21, 2012

problem getting "LIKE @parameter%" to work

Hello,

I need a text box that the user puts in part of a name and hits find and it returns the values that contain the words. so i want the nvarchar value to go into the standard SQL statement below.

SELECT *
FROM table
WHERE column_name LIKE 'nvarchar%'

It works fine in when i type it in manually.

But im using a stored procedure from VS and it will not work with the '%' part

SELECT *
FROM table
WHERE column_name LIKE @.parameter%

Any help or ideas would be greatly appreciated.Hi, my similar line looks like ...


Dim myCommand = New SqlCommand("exec search_telephone '%" & filterValue1 & "%'", myConnection)

... where search_telephone is a stored procedure expecting an input of part of a surname.

NOTE the 2 percentage characters.

Richard|||Like uses a string as its input. So you'd need to use '%' + @.param + '%'|||Is your SQL running inside a stored proc? That's what it sounds like to me.

If that's the case, do something like this:


declare @.strSQL varchar(8000)
select @.strSQL = 'SELECT * FROM table WHERE column_name LIKE ''' + @.parameter + ''''

EXEC ( @.strSQL )

I do this all the time in my stored procs for searches. I haven't found another way to do this. The trick is getting the number of single quotes right.|||It should be:


declare @.strSQL varchar(8000)

select @.strSQL = 'SELECT * FROM table WHERE column_name LIKE ''%' + @.parameter + '%'''

EXEC ( @.strSQL )

but you get the point.

For help debugging these types of "dynamically generated" SQL statements, use PRINT ( @.strSQL ) and run it in query analyzer.|||in your stored procedure this should work and will not require SELECT permissions on the table like an EXEC(@.sql) would.

CREATE PROC [some_search]
@.Search nvarchar(50)
AS

Declare @.LikeSearch nvarchar(52)

-- you could also add do '%' + @.Search + '%' depending on how you want the search to work
SET @.LikeSearch = @.Search + '%'

SELECT *
FROM table
WHERE column_name LIKE @.LikeSearch

sql

No comments:

Post a Comment