SQL语法错误附近')'

时间:2012-05-12 04:31:16

标签: c# sql sql-server-2008

我正在实现一个使用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 ')'

任何解决方案?

2 个答案:

答案 0 :(得分:8)

在插入后,您似乎错过了“结束”。这是未经测试的,但请尝试以下:

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

答案 1 :(得分:1)

插入后错过了“结束”,在第二个插入语句中,请尝试以下内容:

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