c#mysql insert query,如果记录存在则更新

时间:2016-06-29 22:49:34

标签: c# mysql sql insert-query

我正在尝试在表中插入新记录,我有两列

      user_records
 ------------------------
| Attribute |  Datatype  |
|------------------------|
| user_id   | varchar(25)|
| count     | int        |
 ------------------------

查询:

INSERT into user_records Values("nix_1", 0)

但如果用户已经存在,那么它应该将计数增加1

2 个答案:

答案 0 :(得分:0)

在尝试INSERT之前,您将检查记录是否存在。您的查询应符合以下内容。示例适用于SQL Server。

DECLARE @sUserID VARCHAR(25) = "nix_1";    // This should be the parameter passed on into the stored procedure

IF EXISTS(SELECT user_id FROM WHERE user_id = @sUserID)
    // Increase the count
    UPDATE user_records SET count = count  + 1 
        WHERE user_id = @sUserID
ELSE
    // Insert new record
    INSERT INTO user_records Values (@sUserID , 0)

有关EXIST

的信息,请参阅以下链接

EXISTS (Transact-SQL)

SQL EXISTS Operator

Difference between EXISTS and IN in SQL?

答案 1 :(得分:0)

为什么不使用INSERT ... ON DUPLICATE KEY语法?

INSERT INTO user_records (user_id, count) VALUES ('nix_1', 0)
ON DUPLICATE KEY UPDATE count = count + 1;

http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html