Reputation: 27
I'm implementing a C# desktop application that uses SQL server database.
I have this code:
SqlConnection cn = new SqlConnection(@"Data Source=PC;Initial Catalog=FRAT_DB;Integrated Security=True");
SqlCommand cmdSelect = new SqlCommand("select MAX(PhotoID) from Photo", cn);
cn.Open();
SqlDataReader MaxID_Selector = cmdSelect.ExecuteReader();
double maxID = 0;
while (MaxID_Selector.Read())
{
if (MaxID_Selector[0].ToString().Trim() != "")
{
maxID = Convert.ToInt64(MaxID_Selector[0].ToString());
}
}
maxID = maxID + 1;
cn.Close();
SqlCommand cmdb = new SqlCommand(@"IF EXISTS(SELECT * FROM Person WHERE PersonID = @personID) BEGIN UPDATE Person SET PersonID = @PersonID, Name= @Name, Age= @Age,P_Group=@P_Group, Email= @Email END ELSE BEGIN INSERT INTO Person(PersonID,Name,Age,P_Group,Email) values(@PersonID,@Name,@Age,@P_Group,@Email)", cn);
cmdb.Parameters.AddWithValue("@PersonID", personID);
cmdb.Parameters.AddWithValue("@Name", textBox1.Text);
cmdb.Parameters.AddWithValue("@Age", textBox2.Text);
cmdb.Parameters.AddWithValue("@P_Group", textBox6.Text);
cmdb.Parameters.AddWithValue("@Email", textBox5.Text);`
When I run the program and try to save the information, I get this error message: Syntax Error Near ')'
Any solutions?
Upvotes: 0
Views: 1429
Reputation: 4697
Looks like you're missing an "End" after the insert. This is untested, but try below:
SqlCommand cmdb = new SqlCommand(@"IF EXISTS(SELECT * FROM Person WHERE PersonID = @personID)
BEGIN
UPDATE Person SET PersonID = @PersonID, Name= @Name, Age= @Age,P_Group=@P_Group, Email= @Email
END
ELSE
BEGIN
INSERT INTO Person(PersonID,Name,Age,P_Group,Email) values(@PersonID,@Name,@Age,@P_Group,@Email)
END ", cn
);
Upvotes: 8
Reputation: 2630
You missed "End" after the insert, in second insert statement, try below:
SqlCommand cmdb = new SqlCommand(@"IF EXISTS(SELECT * FROM Person WHERE PersonID = @personID) BEGIN UPDATE Person SET PersonID = @PersonID, Name= @Name, Age= @Age,P_Group=@P_Group, Email= @Email END ELSE BEGIN INSERT INTO Person(PersonID,Name,Age,P_Group,Email) values(@PersonID,@Name,@Age,@P_Group,@Email) END ", cn);
Upvotes: 1