SQL:如果存在则更新如果不存在则插入

时间:2016-01-04 10:57:29

标签: sql-server tsql

SQL Server的表格中,我想存储每人折扣码的用法。

我有以下专栏:

  • 用户ID
  • 使用实例

如果代码和userId的组合存在,我想将Usages增加一,如果不是,我想插入一条Usages设置为一的新记录。

单独的查询将是:

INSERT INTO CodeUsages 
VALUS (@code, @user, 1)

或者:

UPDATE CodeUsages
SET Usages = Usages + 1
WHERE UserId = @user
  AND Code = @code

有没有办法将这些查询合并为一个?

2 个答案:

答案 0 :(得分:1)

;WITH cte AS 
(
    SELECT *
    FROM dbo.CodeUsages
    WHERE UserId = @user
        AND Code = @code   
)
MERGE cte t
USING (
    SELECT UserId = @user, Code = @code
) s ON s.UserId = t.UserId AND s.Code = t.Code
WHEN MATCHED
    THEN
        UPDATE SET t.Usages = Usages + 1
WHEN NOT MATCHED BY TARGET
    THEN
        INSERT (UserId, Code, Usages)
        VALUES (s.UserId, s.Code, 1);

答案 1 :(得分:0)

我会在Primary-key上使用try catch

try INSERT INTO CodeUsages VALUS (@code,@user,1) catch UPDATE CodeUsages SET Usages = Usages + 1 WHERE UserId = @user AND Code = @code

  • 只有PRIMARY-KEY你的@code和@user