le tr igger saisit la valeur maximale de t et la stocke dans une variable de table. Le cte calcule le nombre de lignes de chaque insert à t et dans la phase de mise à jour, il l'ajoute à la valeur stockée dans la variable de table.
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
Est-ce que c'est ce que vous voulez réaliser? https://stackoverflow.com/questions/13990596/how-to-get-row-id-in-mysql – endo64
Oui c'est ce que je veux mais avec un code de déclenchement dans [azteca]. [WOCUSTFIELD] table en utilisant [dbo ] [View_1] voir la table, un conseil s'il vous plaît merci d'avance Lubna –
L'URL est pour mysql et ne fonctionnera pas dans sqlserver –