I have a problem using the sql server full text feature. I'm converting some forum software to use the full text search and I have everything setup and working. My problems are related to full text queries. I have designed a few queries which run as desired when I test them in sql server management studio using the CONTAINS predicate to locate my search results eg:
Select ....
From .....
WHERE Contains(p.Message,'" dog food "' ) ......
So this runs fine but how can I parameterize this in a prepared statement? Ideally I would like to be able to run a query with a where clause like:
Select ....
From .....
WHERE Contains(p.Message,'" @SearchTerm "' ) ...
or even
WHERE Contains(p.Message,'"@SearchTerm" Near "@OtherSearchTerm" ) ...
But this approach doesn't work because of the double quotes and all. I could build the search term up dynamically in the code but I really need to be using parameters for all user input for security reasons. I have looked at a zillion google results trying to find a solution but can't(Surely this must happen everyone or am I missing something really obvious here and/or it's not possible ). Any Ideas?
SQL Server places the following restrictions on what types of queries can be parameterized using Simple Parameterization: If you want SQL Server to parameterize your SQL statements you have three options: stored procedures, sp_executesql or Forced Parameterization. Stored procedures always have a query plan created and reused.
Write full-text queries by using the predicates CONTAINS and FREETEXT and the rowset-valued functions CONTAINSTABLE and FREETEXTTABLE with a SELECT statement. This article provides examples of each predicate and function and helps you choose the best one to use.
If you want SQL Server to parameterize your SQL statements you have three options: stored procedures, sp_executesql or Forced Parameterization. Stored procedures always have a query plan created and reused. (Technically they don't always have one but it's close enough for this article. And they don't always reuse it.
Full-text search refers to the functionality in SQL Server that supports full-text queries against character-based data. These types of queries can include words and phrases as well as multiple forms of a word or phrase. To support full-text queries, full-text indexes must be implemented on the columns referenced in the query.
Create a stored procedure with parameters, like:
CREATE PROCEDURE [sp_FullTextSearch]
@SearchTerm nvarchar(500)
AS
BEGIN
Select ....
From .....
WHERE Contains(p.Message, @SearchTerm)
END
Then call it from your code.
HOW TO: Call SQL Server Stored Procedures in ASP.NET by Using Visual C# .NET
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With