我有一個如下所示的查看錶,我想讓名爲「number」的自定義字段具有自動序列號(1,2, ...。)在列CUSTOMFIELDVALUE根據的requestId在特定字段中填寫的自動序列號(1,2,...)
我需要在WOCUSTOMFIELD表的觸發器代碼,做我想做提前
感謝Lubna
我有一個如下所示的查看錶,我想讓名爲「number」的自定義字段具有自動序列號(1,2, ...。)在列CUSTOMFIELDVALUE根據的requestId在特定字段中填寫的自動序列號(1,2,...)
我需要在WOCUSTOMFIELD表的觸發器代碼,做我想做提前
感謝Lubna
的填寫TR igger從t獲取最大值並將其存儲在表變量中。 cte計算每個插入行的行號,並在更新階段將其添加到存儲在表變量中的值中。
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
嗨P.Salmon, 感謝您的幫助, 我仍然有問題的代碼。我們可以使用[dbo]。[View_1]表格而不是闡明表格嗎?或t表類似於[azteca]。[WOCUSTFIELD],我需要在它上面構建觸發器?你怎麼看? 在此先感謝。 Best, Lubna –
觸發器將在插入,更新或刪除時觸發。不是一個觀點。我不清楚這個視圖在這裏有什麼作用,或者你的customfieldvalue應該存儲在wocustfield中,或者你只是想在視圖執行時計算它。 –
這是你想達到的目的嗎? https://stackoverflow.com/questions/13990596/how-to-get-row-id-in-mysql – endo64
是的,這是我想要的,但在[azteca]的觸發代碼。[WOCUSTFIELD]表使用[dbo ]。[View_1]視圖表,任何建議請提前致謝 Lubna –
該網址是爲MySQL和不會在sqlserver中工作 –