2

I'm trying to add a WHERE clause to my SQL statement but get an error:

Incorrect syntax near the keyword 'WHERE'.

when running the program.

My SQL statement

insertCommand.CommandText = "INSERT INTO [UserInformation]  (Password, NewUser) " _
            & "Values('" & Pw1 & "', '" & NewUSR & "') WHERE ([Email] = '" & txtUserName2 & "') "

Any ideas?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection – marc_s Dec 06 '13 at 16:14
  • 1
    makes no sense to have where in insert statement – JC Lizard Dec 06 '13 at 16:22

2 Answers2

4

What is the meaning of a WHERE clause in a INSERT statement?
You should remove everything after the closing parenthesys for the values

Of course, you should also not use string concatenation in sql statements because your code is exposed to Sql Injection

 insertCommand.CommandText = "INSERT INTO [UserInformation]  " & _
                             "(Password, NewUser) Values(@pwd,@newusr)" 
 insertCommand.Parameters.AddWithValue("@pwd", Pw1)
 insertCommand.Parameters.AddWithValue("@new", NewUSR )

Instead, if your plan is to UPDATE the record, then the WHERE is required, but the query text is different

 updateCommand.CommandText = "UPDATE [UserInformation]  " & _
                             "SET Password = @pwd, NewUser = @newusr " & _
                             "WHERE ([Email] = @email) "

If you use parameters to pass your values you remove the possibility of SQL Injection, but another great benefit is that now your query text is not littered with open/close quotes. You leave the correct parsing of your command (including the exact resolution of the parameters) to the underlying database code.

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • 1
    Thanks as soon as you said " What is the meaning of a WHERE clause in a INSERT statement? " I realised I need the UPDATE statement and yours works great! –  Dec 06 '13 at 16:27
0

You'll need to so an INSERT and SELECT combo.

http://technet.microsoft.com/en-us/library/ms188263(v=sql.105).aspx

Mike Cheel
  • 12,626
  • 10
  • 72
  • 101