2014-05-06 64 views
0

我有這樣的代碼,一個POST請求來更新數據庫中的記錄:IF NOT EXISTS,UPDATE語句錯誤

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請求我得到的錯誤:

和 「附近關鍵字‘插入’不正確的語法」,「附近有語法錯誤elseUPDATE'。」

+1

你忘了字符串中的其他人後添加一個空格之後。它應該是「別人」 +「UPDATE – Bedford

+0

您好,感謝您的答覆,我沒有你所說的話,但仍然得到這兩個錯誤」附近關鍵字‘插入’不正確的語法。關鍵字附近 不正確的語法「其他」。」 – Anjola

+1

,你忘了EXIST聲明 – Bedford

回答

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和圍繞「其他」一對夫婦的間距問題

+0

完美!謝謝你的幫助 – Anjola