views:

22

answers:

1

I am adding batches of records to a table using a single insert statement. I want each new batch to be allocated incrementing numbers, but starting from 1 each time.

So, if I have

Batch    Name    IncementingValue
1        Joe     1
1        Pete    2
1        Andy    3
2        Sue     1
2        Mike    2
2        Steve   3

and I then add two records (using a single insert statement) :

3        Dave
3        Paul

How can I run an update statement against this table so that Dave will be set to 1 and Paul to 2. I don't want to use a cursor.

A: 

The ranking function ROW_NUMBER should do what you need. You didn't mention any specific rules about how the sequence number should be allocated, so I've done it here using the name:

INSERT targetTable(Batch,Name,IncementingValue)
SELECT BatchId,
       Name,
       ROW_NUMBER() OVER (ORDER BY Name)
FROM sourceTable
Ed Harper
Great - thanks.
DEH
@Ed - do you know if I can apply these values via an update statement e.g.update SegmentationKeysUnconstrained set batchrownumber=row_number() over (order by trackingtokenid)from SegmentationKeysUnconstrainedwhere batchid='58D73880-31B1-40AF-A749-7F6EBEAAF3E4'
DEH
The problem I have is that I need to apportion one set of row_number() values over several insert statements, so I can't actually use row_number at the point of insertion - I have to do it once several inserts have completed.
DEH
The following did the trick:UPDATE derivedtableSET batchrownumber = rownoFROM ( SELECT batchrownumber, ROW_NUMBER() OVER(PARTITION BY batchid ORDER BY trackingtokenid) AS rowno FROM SegmentationKeysUnconstrained where batchid='58D73880-31B1-40AF-A749-7F6EBEAAF3E4' ) AS derivedtable
DEH