views:

1963

answers:

3

I am trying to build SQL for a parameter query in C# for a query which will contain the LIKE %% command.

Here is what I am trying to acheive (please note that the database is Firebird)

var SQL = string.format("SELECT * FROM {0} WHERE {1} LIKE '%?%'", TABLE, NAME);
Cmd.Parameters.AddWithValue(NAME, "JOHN");

Now I have tried every single permutation to get the parameter to work, I have tried;

  • adding the % character to the parameter,

    Cmd.Parameters.AddWithValue(NAME, "%" + "JOHN" + "%");

  • or

    Cmd.Parameters.AddWithValue(NAME, "'%" + "JOHN" + "%'");

I cannot seem to get this to work, how can I use a parameter for the LIKE query to work.

Suggestion welcome!

A: 

In the past when doing this, i've simply integrated it into the sql, making sure that i replace single quotes with question marks to deal with sql injection. Eg:

var SQL = string.format("SELECT * FROM {0} WHERE {1} LIKE '%{2}%'",
  TABLE,
  NAME,
  JOHN.Replace("'","?"));
Chris
+2  A: 

You can't have parameters inside of a string literal in the query. Make the entire value the parameter, and add the wildcards to the string:

var SQL = string.format("SELECT * FROM {0} WHERE {1} LIKE ?", TABLE, NAME);
Cmd.Parameters.AddWithValue(NAME, "%" + "JOHN" + "%");
Guffa
an example would be ? looks like you just copied my code.
Pay closer attention: he moved the wild cards to the parameter. This will work, but imo it's the wrong way to do it.
Joel Coehoorn
@Myhiad: Notice that there is only ? after the like operator, no wildcard characters and no apostrophes.
Guffa
@Joel Coehoorn: There is no reason to be rude. The question doesn't contain any information about how the query looks after the parameter has been changed.
Guffa
well this was the option that actually worked! thanks Guffa
+2  A: 
var SQL = string.Format("SELECT * FROM {0} WHERE {1} LIKE '%' + ? + '%'", TABLE, NAME);
Cmd.CommandText = SQL;
Cmd.Parameters.Add("?", SqlDbType.VarChar, 50).Value = "JOHN";
Joel Coehoorn
is this SQL valid for Firebird?
I didn't see the firebird requirement. I updated the sql to make sure it's okay, but the parameter code is wrong because the SqlDbType enum was intended for Sql Server. I still like to avoid AddWithValue, though
Joel Coehoorn
this is just not working for me. I am getting the following error;FirebirdSql.Data.FirebirdClient.FbException : Dynamic SQL Errorexpression evaluation not supported ----> FirebirdSql.Data.Common.IscException : Exception of type 'FirebirdSql.Data.Common.IscException' was thrown.