1

I'm trying to write a stored procedure in SQL Server that checks if search input exists in a column.

SELECT * 
FROM Product 
WHERE @Type LIKE @SearchResult

My problem is that when I fetch @Type from user's input, it comes as a string in SQL therefore syntax is wrong and it returns NULL.

Is there a way to get rid off single quotations or convert it to plain text in SQL?

So if @Type is "ProductName" it would appear in SQL as

SELECT * 
FROM Product 
WHERE ProductName LIKE @SearchResult (no single quotes around `ProductName`)
2
  • 1
    This would require dynamic SQL, but would also be vulnerable to SQL injection. Commented Apr 20, 2020 at 23:08
  • That's what I want to avoid so I was wondering if there is a way around it in a stored procedure. Commented Apr 20, 2020 at 23:10

1 Answer 1

1

You have to use dynamic SQL to replace anything other than a constant in a query:

DECLARE @sql NVARCHAR(MAX);

SET @SQL = 'SELECT * FROM Product WHERE  @Type LIKE @SearchResult';

SET @SQL = REPLACE(@SQL, '@Type', @Type);

exec sp_executesql @sql,
                   N'@SearchResult NVARCHAR(MAX)',
                   @SearchResult=@SearchResult;

You can still pass the @SearchResult value using a parameter.

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

1 Comment

@koydek You can use quotename(@Type) to avoid sql injection if needed.

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.