2017-09-10 98 views
0

我有一个如下所示的查看表,我想让名为“number”的自定义字段具有自动序列号(1,2, ...。)在列CUSTOMFIELDVALUE根据的requestId在特定字段中填写的自动序列号(1,2,...)

enter image description here

我需要在WOCUSTOMFIELD表的触发器代码,做我想做提前

感谢Lubna

+0

这是你想达到的目的吗? https://stackoverflow.com/questions/13990596/how-to-get-row-id-in-mysql – endo64

+0

是的,这是我想要的,但在[azteca]的触发代码。[WOCUSTFIELD]表使用[dbo ]。[View_1]视图表,任何建议请提前致谢 Lubna –

+0

该网址是为MySQL和不会在sqlserver中工作 –

回答

0

的填写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 
+0

嗨P.Salmon, 感谢您的帮助, 我仍然有问题的代码。我们可以使用[dbo]。[View_1]表格而不是阐明表格吗?或t表类似于[azteca]。[WOCUSTFIELD],我需要在它上面构建触发器?你怎么看? 在此先感谢。 Best, Lubna –

+0

触发器将在插入,更新或删除时触发。不是一个观点。我不清楚这个视图在这里有什么作用,或者你的customfieldvalue应该存储在wocustfield中,或者你只是想在视图执行时计算它。 –