[英]T-SQL INSERT - Increment value when other columns are duplicated
I have the following 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);
End users will submit data for Year, Region, and Amount through an Excel form, which will use VBA to write INSERT statements against the table. 最终用户将通过Excel表单提交Year,Region和Amount的数据,该表单将使用VBA针对该表编写INSERT语句。 DraftNo will be 1 by default, but if there is already a match in the table on the first two columns (Year and Region), I want to increment DraftNo by one each time. 默认情况下,DraftNo将为1,但是如果前两列(“年份”和“地区”)中的表中已经存在一个匹配项,我想每次将“ DraftNo”加1。
For example, if the application tries to write: 例如,如果应用程序尝试编写:
INSERT INTO Budget VALUES (2018, 'Region1', 600000, 1)
It should be converted to: 它应转换为:
INSERT INTO Budget VALUES (2018, 'Region1', 600000, 2)
Of course, the solution will also need to recognize the max draft number for the Year/Region combination and increment one more from there, rather than always using 2. 当然,解决方案还需要识别Year / Region组合的最大草稿数,并从那里再增加一个,而不是总是使用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)
Using MERGE
: 使用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);
Using Update
+ Insert
: 使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.