Question

I have this code, for a POST request to update a record in a database:

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

But when I try and execute the POST request in the browser I get the errors:

"Incorrect syntax near the keyword 'INSERT'" and "Incorrect syntax near 'elseUPDATE'."

Was it helpful?

Solution

it should be like this

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

I added the ending parantheses after your EXISTS and a couple of spacing issues around "else"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top