T-SQL INSERT - 当其他列被复制时增加值
T-SQL INSERT - Increment value when other columns are duplicated
我有以下 table:
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 表单提交年份、地区和金额的数据,该表单将使用 VBA 针对 table 编写 INSERT 语句。 DraftNo 默认为 1,但如果前两列(年份和地区)的 table 中已经有匹配项,我想每次将 DraftNo 递增 1。
例如,如果应用程序尝试写入:
INSERT INTO Budget VALUES (2018, 'Region1', 600000, 1)
应转换为:
INSERT INTO Budget VALUES (2018, 'Region1', 600000, 2)
当然,该解决方案还需要识别 Year/Region 组合的最大草稿编号并从那里再递增 1,而不是始终使用 2。
如果需要添加新记录,草稿号递增:
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)
我有以下 table:
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 表单提交年份、地区和金额的数据,该表单将使用 VBA 针对 table 编写 INSERT 语句。 DraftNo 默认为 1,但如果前两列(年份和地区)的 table 中已经有匹配项,我想每次将 DraftNo 递增 1。
例如,如果应用程序尝试写入:
INSERT INTO Budget VALUES (2018, 'Region1', 600000, 1)
应转换为:
INSERT INTO Budget VALUES (2018, 'Region1', 600000, 2)
当然,该解决方案还需要识别 Year/Region 组合的最大草稿编号并从那里再递增 1,而不是始终使用 2。
如果需要添加新记录,草稿号递增:
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)