“)”附近的 SQL 语法错误

本文关键字:SQL 语法 错误 | 更新日期: 2023-09-27 18:33:52

我正在实现一个使用 SQL Server 数据库的 C# 桌面应用程序。

我有这个代码:

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);`

当我运行该程序并尝试保存信息时,我收到以下错误消息:Syntax Error Near ')'

有什么解决办法吗?

“)”附近的 SQL 语法错误

看起来您在插入后缺少"结束"。这是未经测试的,但请尝试以下操作:

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
                                 );

插入后您错过了"结束",在第二个插入语句中,请尝试以下操作:

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);