0

I am trying to create table through c# I am using following code

private void Login_Load(object sender, EventArgs e)
    {
        string connectionstring = "server=.;database=Student;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connectionstring);
        string fee_table = @"
  IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'fees') AND   type in (N'U')) CREATE TABLE user (user_name char(50),password char(50));";

        conn.Open();
        SqlCommand cmd = new SqlCommand(fee_table, conn);
        cmd.ExecuteNonQuery();
    }

but iam getting runtime error syntax error near user

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Aman
  • 9
  • 7
  • Hi, What error are you getting? – Harry Jul 08 '14 at 11:42
  • 1
    The first Google result for "ms-sql syntax error near user" is [this SO Q&A](http://stackoverflow.com/questions/20543395/c-sharp-syntax-error-near-table-name), which is closed as a duplicate of [Creating table names that are reserved words/keywords in MS SQL Server](http://stackoverflow.com/questions/695578/creating-table-names-that-are-reserved-words-keywords-in-ms-sql-server). Please try to search first. – CodeCaster Jul 08 '14 at 11:44
  • Incorrect syntax near 'user1'. – Aman Jul 08 '14 at 11:46
  • @user3809448: I doubt this. Can you copy this query in sql and see if there is any error? – Nikhil Agrawal Jul 08 '14 at 11:50
  • it is running sucessfully without[] – Aman Jul 08 '14 at 11:59

3 Answers3

4

user is a keyword in many databases. You either need to change the name of the table or quote it. For example, in SQL Server do this:

CREATE TABLE [user] (user_name char(50),password char(50))

In other database systems you may be able to use:

CREATE TABLE "user" (user_name char(50),password char(50))

Or:

CREATE TABLE 'user' (user_name char(50),password char(50))
DavidG
  • 113,891
  • 12
  • 217
  • 223
2

User is a reserved keyword. Change it to [user].

enter image description here

Change to

enter image description here

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
1

USER is a reserved keyword in T-SQL. You should use it with squared brackets []. However, the best solution is to change the name to a nonreserved word.

Also use using statement to dispose your SqlConnection and SqlCommand.

string connectionstring = "server=.;database=Student;Integrated Security=True";
using(SqlConnection con = new SqlConnection(connectionstring ))
using(SqlCommand cmd = con.CreateCommand())
{
     ...
     con.Open();
     cmd.ExecuteNonQuery();
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364