Getting the following error when tried inserting data in multiple tables.
Incorrect syntax near the keyword 'User'
Button Click Code:
private void buttonSave_Click(object sender, EventArgs e) {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleTest1.Properties.Settings.SampleTestDBConnectionString"].ConnectionString);
SqlCommand cmd = conn.CreateCommand();
try {
UserId = UserId + 1;
cmd.CommandText = "INSERT INTO [User](User_Id,Name,Gender,Is_Active,Created_Date,Activated_Date) values(@userid,@name,@gender,@isactive,@createdate,@activedate)";
conn.Open();
cmd.Parameters.AddWithValue("@userid", SqlDbType.Int).Value = UserId;
cmd.Parameters.AddWithValue("@name", SqlDbType.VarChar).Value = textBoxName.Text;
cmd.Parameters.AddWithValue("@gender", SqlDbType.VarChar).Value = textBoxGender.Text;
cmd.Parameters.AddWithValue("@isactive", SqlDbType.Bit).Value = "True";
cmd.Parameters.AddWithValue("@createdate", SqlDbType.Date).Value = System.DateTime.Today;
cmd.Parameters.AddWithValue("@activedate", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO User_Details(User_Id,Mobile,Address,Job_Contract) values(@userid,@mobile,@address,@jobcontract)";
cmd.Parameters.AddWithValue("@userid", SqlDbType.Int).Value = UserId;
cmd.Parameters.AddWithValue("@mobile", SqlDbType.VarChar).Value = textBoxMobile.Text;
cmd.Parameters.AddWithValue("@address", SqlDbType.VarChar).Value = textBoxAddress.Text;
cmd.Parameters.AddWithValue("@jobcontract", SqlDbType.VarChar).Value = textBoxJobContract.Text;
cmd.ExecuteNonQuery();
conn.Close();
}
I have declared UserId
value as
static int UserId = 100;
Not sure what went wrong. Please do comment if more details required.
REFERENCES:
LINK 1 : ASP.NET C# Insert data into multiple table
LINK 2 : Insert into two tables at once.
LINK 3 : Getting Syntax error in Insert statement
LINK 4 : Insert Data into two tables simultaneously in SQL Server