4

We have a web site with a search box. The search uses a fulltext index column. However, we just cant feed the text the user has input into this stored procedure.

CREATE PROCEDURE [dbo].[SearchPages]
    @Term varchar(200)
AS
BEGIN
    SELECT pc.SearchData, from PageContent pc
    where contains(pc.SearchData, @Term)
END

Searches with space in them fails, also there is a pletora of sql functions we do not want to expose to the users like

NEAR((bike,control), 10, TRUE)

and the like or binary operators like AND or OR.

So we need to escape the term in some way.

One way that immediately comes in mind is to put an AND between every word. However, it doesnt feel acceptable.

So is there any better suggestions?

2 Answers 2

1

Here are three suggestions.

Suggestion 1. Use plainto_tsquery when you convert the user provided search string to PostgreSQL's tsquery, see the PostgreSQL docs. — I think that plainto_tsquery discards any special magical characters + AND, OR etcetera. (But I'm not completely sure. You'd better verify this so you don't do anything dangerous) Oops I didn't notice that this was about SQL Server not PostgreSQL.

Suggestion 2. Build a HTML form for advanced search queries, with fields like:

Include all these words: ...
Include any of these words: ...
Exclude all these ...

And so on. Next, construct the otherwise dangerous full text search expression yourself in SQL Server syntax.

Suggestion 3. You could provide a single search text field, and let e.g. "-someword" mean that "someword" should be excluded, and "+anotherword" mean that "anotherword" must be included. Then, you build your own parser for this search field, and convert the resulting "abstract search tree" to something SQL Server understands, and give it to SQL Server.

3
  • Uh, this question is tagged [sql-server].
    – Jon Seigel
    Jul 13, 2013 at 15:18
  • @JonSeigel You're correct. Now I edited/fixed my answer. (I was searching for PostgreSQL and had only PostgreSQL in my mind)
    – KajMagnus
    Jul 13, 2013 at 15:27
  • But what I wanted was a totally stupid search function where you can not exclude any words or use any finesses. Jul 13, 2013 at 22:45
0

Sql Server has a FREETEXT() function which works great for these kinds of queries.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.