在SQL Server
的表格中,我想存储每人折扣码的用法。
我有以下专栏:
如果代码和userId
的组合存在,我想将Usages
增加一,如果不是,我想插入一条Usages
设置为一的新记录。
单独的查询将是:
INSERT INTO CodeUsages
VALUS (@code, @user, 1)
或者:
UPDATE CodeUsages
SET Usages = Usages + 1
WHERE UserId = @user
AND Code = @code
有没有办法将这些查询合并为一个?
答案 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