0

Statement:

declare @Searchkey varchar(50)='a'
declare @Sql nvarchar(max) =''

set @Sql = @Sql + 
    'select * from products where upper(ProductName) like %' + upper(@Searchkey) + '%'

execute sp_executesql @Sql

Error message:

Msg 102 Level 15 State 1 Line 1
Incorrect syntax near 'A'.

2
  • 3
    The like wildcard % should be inside the string. Commented May 15, 2020 at 6:22
  • 1
    It would appear you believe that sp_executesql protects you from SQL injection. It does not. It would have if you used parameters when calling it. Commented May 15, 2020 at 7:01

3 Answers 3

1

You do not require a dynamic query for such case, you can use below simple query to get the desired result.

declare @Searchkey varchar(50)= 'a'
select * from products where upper(ProductName) like  '%' + upper(@Searchkey) + '%' 

If you still want to go with Dynamic query then below are the connect syntax.

declare @Searchkey varchar(50)='a'
declare @Sql nvarchar(max) =''

set @Sql =@Sql+'select * from products where upper(ProductName) like ''%' +upper(@Searchkey)+'%'''

--print @Sql
execute sp_executesql @Sql

Note: Whenever you will get an error with a dynamic query then the best way is to print the query using print statement that will help to identify the error easily. In your case, a single quote was missing.

Sign up to request clarification or add additional context in comments.

Comments

1

The reason for this error is that you need to add quotes around the search pattern, when you build the dynamic statement. But I think that your should use parameter in this dynamically built statement to prevent SQL injection issues:

DECLARE @Searchkey varchar(50) = 'a'
DECLARE @Sql nvarchar(max) = N''

SET @Sql = 
    @Sql + 
    N'SELECT * FROM products WHERE UPPER(ProductName) LIKE CONCAT(''%'', UPPER(@Searchkey), ''%'')'

PRINT @Sql
EXEC sp_executesql @Sql, N'@Searchkey varchar(50)', @Searchkey

Comments

0

You're not placing quotes around your search term, so the literal query that's being sent is:

select * from products where upper(ProductName) like %A%

You need to wrap the search term in quotes, like so:

set @Sql =@Sql+'select * from products where upper(ProductName) like ''%'+upper(@Searchkey)+'%'''

This will create the following query:

select * from products where upper(ProductName) like '%A%'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.