tags:

views:

107

answers:

5

Hi folks,

from my C#-programm, I access a SQL Server 2008 Database. I have a table with a fulltextindex and want to search for an indexed entry:

SELECT page_id FROM page_categories WHERE page_title LIKE @title

When 'title' has no withespaces everything is fine, but when title does contain withespaces, the request fails. It throws no error, but the returned recordset is closed

command.ChangeParameter("title", title);

using (System.Data.IDataReader reader = command.ExecuteQuery())
{
  while (reader.Read())
    resultSet.Add(reader.GetInt32(0));

  reader.Close();
}

I cannot enclose the @title parameter with '', because then the Command-Object would interpret the @title as a string and not a parameter.

SELECT page_id FROM page_categories WHERE page_title LIKE '@title'

Anyone knows how I can use a parameter for the LIKE request when the title-parameter can contain whitespace?

Thanks in advance, Frank

+2  A: 

You can do this:

SELECT page_id 
FROM page_categories 
WHERE page_title LIKE '%' + @title + '%'
ck
I want to match the exact string. Let's say, I have 'tool' and 'tool songs' in my database. When I search with title="tool", I want to get ONLY the row with the value 'tool', not 'tool songs'. But this would be the case, when I use wildcards ...
Aaginor
Then you should be able to do where page_title = @title. Maybe you need to provide better examples...
ck
What I want to do is relative simple: I have a table with a nvarchar-string and an id. I want to get the id(s) - i can't be sure that the nvarchar is unique - for a given string.
Aaginor
+2  A: 

alternatively to the ck's answer, you could do this:

command.ChangeParameter("title", "%"+title.Trim()+"%");
ammoQ
+1  A: 

You don't use LIKE to search a freetext index. You use CONTAINS or FREETEXT or similar.

erikkallen
Ah, thanks. But my problem remains the same: SELECT page_id FROM page_categories WHERE CONTAINS (page_title, @title) will not work, when the value of title contains withespaces. It throws a syntax error.
Aaginor
+1  A: 
SELECT page_id 
FROM page_categories 
WHERE page_title LIKE '%' + @title + '%'

The % represents a wild char similar to the more common * outside SQL (Any string of zero or more characters).

You should make sure that in the calling code the parameter is trimmed via .Trim().

Here is the full reference of possible wildchars.

Johannes Rudolph
A: 

I add the single quotes to the query:

SELECT page_id FROM page_categories WHERE page_title LIKE '' + @title + ''

If I try this with 'Contains' ( CONTAINS (page_title, '' + @tile + '') ), I get a syntax error.

Aaginor