如果不是EXISTS,UPDATE语句错误

时间:2014-05-06 23:24:02

标签: c# asp.net sql database post

我有这个代码,用于更新数据库中记录的POST请求:

    if (Server.HtmlDecode(Request.RequestType).Equals("POST"))
    {
        string connectionstring = @"Data Source=sql2008.net.dcs.hull.ac.uk;Initial Catalog=rde_440881;Integrated Security=True";
        SqlConnection con = new SqlConnection(connectionstring);
        con.Open();

        string FullName = null;
        FullName = Request.QueryString["FullName"];

        string Location = null;
        Location = Request.QueryString["Location"];

        string Username = "default";           
        string TimeOfLastUpdate = "default";

        SqlCommand command = new SqlCommand("IF NOT EXISTS(SELECT (FullName) FROM [Staff] WHERE [FullName] = @FullName" + " INSERT INTO [Staff] ([Username], [FullName], [Location], [TimeOfLastUpdate]) VALUES (@Username, @FullName, @Location, @TimeOfLastUpdate)" + "else" + "UPDATE [Staff] SET [Location] = @Location, [TimeOfLastUpdate] = @TimeOfLastUpdate WHERE [FullName] = @FullName", con);
        command.Parameters.AddWithValue("@UserName", Username);
        command.Parameters.AddWithValue("@FullName", FullName);
        command.Parameters.AddWithValue("@Location", Location);
        command.Parameters.AddWithValue("@TimeOfLastUpdate", TimeOfLastUpdate);
        command.ExecuteNonQuery();
        Response.Write("The location is now" + Location);
        con.Close();
    }

但是当我尝试在浏览器中执行POST请求时,我得到错误:

"关键字' INSERT'"附近的语法不正确和 "' elseUPDATE'。"

附近的语法不正确

1 个答案:

答案 0 :(得分:1)

应该是这样的

SqlCommand command = new SqlCommand("IF NOT EXISTS(SELECT (FullName) FROM [Staff] WHERE [FullName] = @FullName) " + 
    "INSERT INTO [Staff] ([Username], [FullName], [Location], [TimeOfLastUpdate]) VALUES (@Username, @FullName, @Location, @TimeOfLastUpdate) " + 
    "else" + 
    " UPDATE [Staff] SET [Location] = @Location, [TimeOfLastUpdate] = @TimeOfLastUpdate WHERE [FullName] = @FullName ", con);

我在你的EXISTS之后添加了结束的parantheses和#34;其他"

的几个间距问题