3

I Sql server i use this command to insert value and if the id already exist update the vale

string commandLine = "IF NOT EXISTS(SELECT clientid FROM Rating WHERE clientid = " + clientId + " AND userid = " + userid + ") " +
            "INSERT INTO Rating VALUES(@clientId,@userid,@rating) " +
            "ELSE " +
            "UPDATE Rating SET rating=@rating WHERE clientid = " + clientId + " AND userid = " + userid + ";";

And i now move to MySQL and this command won't work. there is any thing same in MySQL?

1
  • What doesn't work? Does it give you an error? Also, your code looks a bit confused. You appear to be switching between concatenating values into your sql(bad!!!), and using parameters (good!!!). It might make things a bit easier if you straighten that out. Commented Feb 26, 2013 at 22:42

2 Answers 2

7

The INSERT ... ON DUPLICATE KEY UPDATE provides an easier syntax in MySQL and also gives you feedback as to what was happening via the affected-rows API call. Few people realise in my experience how handy it can come in your program logic to know that:

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values.

Sign up to request clarification or add additional context in comments.

2 Comments

And if i don't have promary key?
Then add one. You should have one. Try learning about indexing in MySQL because it makes a big difference if you use them properly. This is a good place to start
2

If you have unique constraint or primary key on clientid, userid you can use INSERT ... ON DUPLICATE KEY UPDATE Syntax

INSERT INTO Rating VALUES(@clientId,@userid,@rating)
ON DUPLICATE KEY
UPDATE Rating SET rating=@rating

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.