Reputation: 3279
I want to perform a small SQL server search in my ASP.NET web project. My database is not big so I think it's better not to use full-text-search.
I want to perform a simple search like this:
select * from mytable where columnA LIKE '%something%'
I can use =
in the following way:
select * from mytable where columnA='"+myVariable+"'
but how can I use a variable instead of %something%
in the LIKE phrase?
Is this correct:
LIKE '"+%myVariable%+"'
?
Upvotes: 15
Views: 46725
Reputation: 386
If you are worried about sql injection, try something like this instead. It's more complex, but it works and should satisfy security requirements. Let's say someone passed a value into your stored procedure using a parameter called "@searchstring".
DECLARE @searchString nvarchar(100) = 'test',
@SQL nvarchar(max),
@foundSearchHit bit,
@paramdef nvarchar(max) = '@foundSearchHit bit OUTPUT'
SET @searchstring = '%' + @searchString + '%'
SET @SQL = '
SELECT TOP 1 @foundSearchHit = 1
FROM sys.databases WHERE [name] like ' +
QUOTENAME(@searchString,'''')
EXEC sp_executeSQL @SQL, @paramdef, @foundSearchHit = @foundSearchHit OUTPUT
SELECT @foundSearchHit
That should do the trick.
Upvotes: 0
Reputation: 1216
In case someone else stumbles into this post like I did. On SSMS 2012 with a SQL 2012 Server back end I was able to use code as follows without issues.
Declare @MyVariable
Set @MyVariable = '%DesiredString%'
Select *
From Table_A
Where Field_A like @MyVariable
Then each time you want to change the Desired String just change it at the Set statement.
I know this post was made prior to 2012 that is why I am mentioning it in case someone with a newer setup looks up this post.
Upvotes: 1
Reputation: 5284
I just tried this and found you can do as below:
SELECT * FROM whatever WHERE column LIKE '%'+@var+'%'
Upvotes: 5
Reputation: 21
DECLARE @myVariable varchar(MAX)
SET @myVariable = 'WhatYouAreLookingFor'
SELECT * FROM mytable
WHERE columnA LIKE '%' + @myVariable + '%'
Upvotes: 1
Reputation: 51
Try this query:
select * from tablename where colname like '%' + @varname + '%'
Hope it helps.
Upvotes: 5
Reputation: 3399
Well you could do something like:
var query = "SELECT * FROM MyTable WHERE columnA LIKE '%" + myVariable + "%'";
Upvotes: 0