saikat mukherjee saikat mukherjee - 2 months ago 7
ASP.NET (C#) Question

How to Solve Sql Command error invalid syntax near the keyword 'user'

I am trying to connect and fetch data from the table

dbo.user
but getting an error as Invalid syntax near the keyword 'dbo.user'
below is my code

private DataTable GetData()
{

string constr = ConfigurationManager.ConnectionStrings["PoojaDBConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{

using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.user"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}


I am getting the issue in
sda.Fill(dt);
statement

Answer

user is an SQL reserved word. Change the query to:

"SELECT * FROM dbo.[user]"

It is always preferred to decorate schema / table / column names with [] to avoid these errors.

Docs:

ODBC Reserved Keywords are reserved for use in ODBC function calls. These words do not constrain the minimum SQL grammar; however, to ensure compatibility with drivers that support the core SQL grammar, applications should avoid using these keywords.