Question

I want to be able to take content from a web page text box and pass it to a SQL Server stored proc that will perform a search on a full-text catalog.

In C#, we are using a SQL Command object to setup parameters needed to call on a stored procedure: one of the parameters contains the query text:

public List<SearchItems> mySearchFunction(string query.....)
{
   blah//....

    SqlParameter paramQry = new SqlParameter();
    paramQry.ParameterName = "@qry";
    paramQry.SqlDbType = SqlDbType.NVarChar;
    paramQry.Direction = ParameterDirection.Input;
    paramQry.Value = query;
    cmd.Parameters.Add(paramQry);

    ......
}

On the SQL side of things, the stored proc will use the query text as:

SELECT RequiredColumns
FROM tableName
WHERE CONTAINS((ourTableField), @qry).....

This is fine for simple (one-word) search terms. How do I convert/pass multi-word or phrases in C# to work in SQL?

For example, if a user enters "Barack Obama" in the text field, we would want to setup the @qry value passed to the SP to look this in the query:

WHERE CONTAINS((ourTableField),'"Barack" AND "Obama"')

Do I need to do some sort of string construction in C#? I have tried this by trying to insert AND and quote literals, but the issue of escaping single and double quotes is tripping me up, and I am concerned this is not a sensible or safe way to continue trying.

I have been trying to build this in C# using a StringBuilder object, along the lines of:

   List<string> queryParts = query.Split(' ').ToList();
   string queryVal = string.Empty;

    if (queryParts != null & queryParts.Count > 0)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("'");

        foreach (string searchPart in queryParts)
        {
           sb.Append("\"" + searchPart + "\"" + "AND");                
        }
        //bit hacky, removing trailing AND         
        sb.Append("'");
        sb.Replace("AND'", string.Empty);
        sb.Append("'");

        queryVal = sb.ToString();

        return queryVal 


       Then assign paramQry.Value = queryVal;

However this results in escaping - slashes etc. being returned. I am sure this is not just a case of Visual Studio rendering these characters in the debugger -the exception that comes back is SQLException.

I have seen similar posts where it is mentioned that the Parameter object can handle escaping, but I cannot see how this works or find any clear examples that may help.

If this is not feasible, does this mean doing some sort of string manipulation in SQL?

This type of solution is new to me, so TIA for advice offered.

Was it helpful?

Solution

You can use StringBuilder to construct your sentence by adding and to every empty space, and build a sentence out of the content of the textbox

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top