views:

135

answers:

3

I have a table which has a column labeled 'sortorder' which is used to allow customer to manually change the order of each item. The table also has a column labeled 'CategoryId'.

I was curious, if I was bulk importing a set of data in which I knew all data, including CategoryId, how I could specify the incrimenting value for 'SortOrder' inside the query, so that it went from 1 to X within each unique CategoryId.

Thanks everyone.

+9  A: 

I'm not sure I understand your question but I think what you're asking is how to synthesize an appropriate SortOrder during an insert into the table. You should use ROW_NUMBER() with partitioning by CategoryId. Of course you will need to define a sorting criteria that gives the propert order of '1 to X':

INSERT INTO myTable (SortOrder, CategoryId, <other columns> ...)
SELECT ROW_NUMBER() OVER (PARTITION BY CategoryId ORDER BY mySortCriteria)
  , CategoryId
  , <other columns> ...
  FROM SourceTable;
Remus Rusanu
You saved my day, thanks. I know about ROW_NUMBER() for SQL 2005, but I did not know about the PARTITION BY parameter.Thanks a bunch.
Kyle B.
Windowing functions FTW! May not work on something other SQL Server 2005, though.
sheepsimulator
good answer - you beat me to it :)
Scott Ivey
Excellent answer +1
Jose Basilio
@Scott is a dog eat dog worlf here on SO lol ;)
Remus Rusanu
+1  A: 

Sounds like you're needing to use the row_number function in your import.

INSERT MyTable(SortOrder, ...)
SELECT  SortOrder = row_number() over (partition by CatgoryID order by SomeOtherField), ...
FROM    MyTable
Scott Ivey
A: 

For anyone who might come along later who is still in SQL Server 2000, here is another way to accomplish the task.

Using a staging table of some sort to fix up the data from the bulk insert. Make sure it has a column called sortorder which is initally populated with a 1 and an identity based id column.

then you can update this with a self join, something like

update t
set sortorder = t1.sortorder +1
from test t
join Test t1 on t.id = t1.id+1

Then put the data into your prod table.

HLGEM