1

I'm getting a sqlexception while im trying to select some values. The error: Incorrect syntax near '@navn'. I've looked around to find other questions similar to mine, but I can't find anything worth to me.

My code:

public List<Vare> findvareAdvanced(string varenavn)
    {
        Vare v = new Vare();
        List<Vare> lv = new List<Vare>();

        SqlConnection myCon = DBcon.getInstance().conn();

        string query = string.Format("SELECT * FROM Vare WHERE Navn LIKE %@navn%");

        myCon.Open();
        SqlCommand com = new SqlCommand(query, myCon);
        com.Parameters.AddWithValue("navn", varenavn);
        SqlDataReader dr = com.ExecuteReader();
        if (dr.Read())
        {
            v.Stregkode = dr.GetString(0);
            v.Navn = dr.GetString(1);
            v.Pris = dr.GetDecimal(2);
            v.Varegruppenr = dr.GetInt32(3);
            lv.Add(v);

        }
        myCon.Close();




        return lv;
    }
Anders Jensen
  • 209
  • 1
  • 4
  • 12

3 Answers3

2

Try,

 string query = string.Format("SELECT * FROM Vare WHERE Navn LIKE @navn");

 com.Parameters.AddWithValue("@navn", "%" + varenavn + "%");
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • +1 for thinking about what he was actually trying to do. You could also add `WHERE Navn LIKE ('%' + @navn + '%')` to your answer; for the case where he can't change the parameter value. – Jonathan Dickinson Oct 11 '11 at 12:38
0

If you want a literal translation of the string, add an @ symbol before the string. This will help handle escape characters

This question might also help

string query = string.Format(@"SELECT * FROM Vare WHERE Navn LIKE %@navn%");
Community
  • 1
  • 1
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
0

forgot the ' ?

string query = string.Format("SELECT * FROM Vare WHERE Navn LIKE '%@navn%' ");
juergen d
  • 201,996
  • 37
  • 293
  • 362