0

I want to write a trigger to transfer some columns of all inserted rows in a table to another table while incrementing the maximum number in a sequence number field in the destination table. this field is not auto increment but is a primary key field.

What I used to do was find the max sequence no in destination table, increment and then insert the new value. This worked fine if data is inserted row at a time. But when many rows are inserted from a single query, how can I increment the sequence number? Sample problem follows:

insert into [mssql].mssql.dbo.destination_table (name,seq_no)
select name,?
from inserted

even few thousand rows can be inserted at once.

seq_no is part of a composite primary key. So for example if data is inserted under different name seq_no will be different. (This requirement should be considered when I can increment the seq_no without considering its part in the primary key)

4

1 回答 1

0

好的,我有你的问题,试试这个

insert into [mssql].mssql.dbo.destination_table (name,seq_no)
select name, x.MaxSeq + row_number() over (order by name)
   from inserted, (select Max(seq_no) As MaxSeq From source_table) x
于 2012-05-04T01:39:04.247 回答