As a sentence and prepared expression

I am trying to make an SQL query with a LIKE clause using a prepared statement.

Here is the code:

using (SqlConnection Connection = new SqlConnection(ConnectionString))
      {
         Connection.Open();
         string Query = "SELECT TOP 10 Field FROM Table WHERE Field LIKE '@pseudopart%'";
                using (SqlCommand Command = new SqlCommand(Query, Connection))
                {
                    Command.Parameters.AddWithValue("@pseudopart", pseudoPart);
                    using (SqlDataReader Reader = Command.ExecuteReader())
                    {
                        if (!Reader.HasRows)
                            return PossibleMatch;
                        while (Reader.Read())
                        {
                            PossibleMatch.Add(Reader["Field"].ToString());
                        }
                    }
                }
            }

The reader is always empty, what am I doing wrong?

+4
source share
2 answers

Since you are using a single quote, it sees your part @pseudopart%as a string literal , not a parameter.

This is why you filter your column Fieldusing a row @pseudopart%rather than a variable pseudoPart. That is why your reader is empty.

Use it instead:

string Query = "SELECT TOP 10 Field FROM Table WHERE Field LIKE @pseudopart";
..
Command.Parameters.AddWithValue("@pseudopart", pseudoPart + "%");

, AddWithValue. . Add() , SqlDbType .

, TABLE T-SQL. , [TABLE]. (Table - TABLE), SQL Server .

- .

+5

% , ado.net sql-, :

 string Query = "SELECT TOP 10 Field FROM Table WHERE Field LIKE @pseudopart";
 using (SqlCommand Command = new SqlCommand(Query, Connection))
 {
     Command.Parameters.AddWithValue("@pseudopart", string.Concat(pseudoPart, "%"));
0

All Articles