我有一个如下所示的视图表,我想让名为“number”的自定义字段按照REQUESTID
在CUSTOMFIELDVALUE列中填写自动序列号(1,2,...)。我需要在WOCUSTOMFIELD表上执行我想要的触发器代码
先谢谢 Lubna
答案 0 :(得分:0)
触发器从t获取最大值并将其存储在表变量中。 cte将每个插入的行号计算为t,并在更新阶段将其添加到表变量中存储的值。
use sandbox
go
--drop table t
--create table t(workid int identity, requestid int,customfieldvalue int)
--go
IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[tGenCustomid]'))
drop trigger tGenCustomid
go
CREATE TRIGGER tGenCustomid
ON t
after insert
AS
BEGIN
DECLARE @max TABLE (
workid int,
requestid int,
customfieldvalue int
);
INSERT INTO @max (requestid,customfieldvalue)
select requestid,
coalesce(max(customfieldvalue),0)
from t
group by requestid
;with cte as
(select i.workid,i.requestid, row_number() over (partition by i.requestid order by i.workid) rn,
m.customfieldvalue
from inserted i
join @max m on m.requestid = i.requestid
)
update t
set customfieldvalue = cte.rn + cte.customfieldvalue
from t
join cte on cte.workid = t.workid and cte.requestid = t.requestid
END;
go
SET NOCOUNT ON
truncate table debug_table
truncate table t
print 'First bunch of inserts'
insert into t(requestid, customfieldvalue)
values
(1,0),(1,0),
(2,0),(2,0),(2,0),
(3,0)
select * from t
print 'Second bunch of inserts'
insert into t(requestid, customfieldvalue)
values
(1,0),(1,0)
select * from t
print 'Third bunch of inserts'
insert into t(requestid, customfieldvalue)
values
(1,0),(4,0),(3,0)
select * from t
First bunch of inserts
workid requestid customfieldvalue
----------- ----------- ----------------
1 1 1
2 1 2
3 2 1
4 2 2
5 2 3
6 3 1
Second bunch of inserts
workid requestid customfieldvalue
----------- ----------- ----------------
1 1 1
2 1 2
3 2 1
4 2 2
5 2 3
6 3 1
7 1 3
8 1 4
Third bunch of inserts
workid requestid customfieldvalue
----------- ----------- ----------------
1 1 1
2 1 2
3 2 1
4 2 2
5 2 3
6 3 1
7 1 3
8 1 4
9 1 5
10 4 1
11 3 2