T-SQL INSERT-当其他列重复时的增量值

时间:2019-01-17 23:51:09

标签: sql sql-server insert conditional increment

我有下表:

CREATE TABLE Budget (
Year Int,
Region varchar(50),
Amount float,
DraftNo int);

GO

INSERT INTO Budget 
VALUES
(2018, 'Region1', 500000, 1),
(2018, 'Region2', 400000, 1),
(2018, 'Region3', 300000, 1);

最终用户将通过Excel表单提交Year,Region和Amount的数据,该表单将使用VBA针对该表编写INSERT语句。默认情况下,DraftNo将为1,但是如果前两列(“年份”和“地区”)中的表中已经存在匹配项,则我想每次将DraftNo都加1。

例如,如果应用程序尝试编写:

INSERT INTO Budget VALUES (2018, 'Region1', 600000, 1)

应将其转换为:

INSERT INTO Budget VALUES (2018, 'Region1', 600000, 2)

当然,解决方案还需要识别Year / Region组合的最大草稿数,并从那里再增加一个,而不是总是使用2。

1 个答案:

答案 0 :(得分:0)

如果您需要添加具有递增DraftNo的新记录:

declare @y int = 2018, @r varchar(50) = 'Region6', @a float = 3

INSERT INTO Budget VALUES (@y, @r, @a, isnull((select max(DraftNo) from Budget where [Year] = @y and Region = @r), 0) + 1)

如果您需要更新现有记录并添加DraftNo:

使用MERGE

merge Budget as trg
using (select 2018, 'Region1', 600000) as src (y, r, a)
on trg.[Year] = src.y and trg.[Region] = src.r and trg.Amount = src.a
when matched then
    update set DraftNo = DraftNo + 1
when not matched then
    insert ([Year], Region, Amount, DraftNo)
    values (y, r, a, 1);

使用Update + Insert

declare @y int = 2018, @r varchar(50) = 'Region6', @a float = 3

update Budget 
set DraftNo = DraftNo + 1
where [Year] = @y and [Region] = @r and Amount = @a

if @@ROWCOUNT = 0
    insert Budget (Year, Region, Amount, DraftNo)
    values (@y, @r, @a, 1)