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`)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.