0

I use this code in my project (SQL COMPACT):

"select Name 
from Drug 
where Name 
like '" + Dname + "%'  
limit 10"

Dname is a string value. The result is this error:

There was an error parsing the query.

[ Token line number = 1,Token line offset = 44,Token in error = LIMIT ]

Why is this happening and how can I fix it?

Community
  • 1
  • 1

3 Answers3

4

i think what you want is

"select TOP (10)  
from Drug 
where Name 
like '" + Dname + "%'  "

you should also try using parametrized queries:

 string qry = "select TOP(10) from Drugs where name like @dname";
 SqlCommand oCmd = new SqlCommand(qry, ConnectionString);
 oCmd.Parameters.AddWithValue("@dname", dname +  '%');
Thousand
  • 6,562
  • 3
  • 38
  • 46
  • using this code too give me an error: There was an error parsing the query. [ Token line number = 1,Token line offset = 12,Token in error = 10 ] –  Mar 16 '13 at 18:24
  • when i remove limit or top it worked corrct.but when i use them again ...error. –  Mar 16 '13 at 18:27
  • again: what's the error? can you try the run the same query in your local SQL server and see if it works there? – Thousand Mar 16 '13 at 18:31
  • There was an error parsing the query[ Token line number = 1,Token line offset = 12,Token in error = 10 ] i haven't a sql server.its sql compact 3.5 –  Mar 16 '13 at 18:34
3

Never use string concatenations to build SQL queries. Always use parametrized queries:

string connectionString = ....
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT TOP 10 FROM drug WHERE name LIKE @name";
    cmd.Parameters.AddWithValue("@name", Dname + '%');
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            ...
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

According to this previous question, the proper syntax is TOP(n), so try this:

"select TOP(10) Name 
from Drug 
where Name 
like '" + Dname + "%' "
Community
  • 1
  • 1
BellevueBob
  • 9,498
  • 5
  • 29
  • 56