AOB
Registered User.
- Local time
- Today, 04:27
- Joined
- Sep 26, 2012
- Messages
- 617
I have a number of tables which include a SortOrder column (i.e. to allow the contents to be sorted in a query based on some attribute other than simple alphabetical or numerical order of a particular field or combination of fields)
The SortOrder field is a simple numeric one - as a general rule, I use iterations of 100 to provide an ample "gap" in which to insert new records, for example :
I want to write a query that "cleans-up" this SortOrder when new records are added, to restore that standard gap of 100 between each record, for example :
In other words, create some sort of ranking query based on the existing SortOrder values, then update the SortOrder values based on that ranking
Here's my ranking query :
But I can't perform the update with this as a sub-query...
...as :
Any suggestions as to how I might go about this? Preferably as efficiently as possible; the tables are relatively small but I'd like something nice and quick that I can just fire whenever a new record is added or an existing record deleted (or, an existing record is updated with a different SortOrder) to keep that field nice and neat?
Thanks
AOB
ID | Value | SortOrder |
---|---|---|
4 | ABC | 100 |
2 | DEF | 200 |
3 | GHI | 300 |
1 | JKL | 400 |
The SortOrder field is a simple numeric one - as a general rule, I use iterations of 100 to provide an ample "gap" in which to insert new records, for example :
ID | Value | SortOrder |
---|---|---|
4 | ABC | 100 |
2 | DEF | 200 |
6 | PQR | 250 |
3 | GHI | 300 |
5 | MNO | 350 |
1 | JKL | 400 |
I want to write a query that "cleans-up" this SortOrder when new records are added, to restore that standard gap of 100 between each record, for example :
ID | Value | SortOrder |
---|---|---|
4 | ABC | 100 |
2 | DEF | 200 |
6 | PQR | 300 |
3 | GHI | 400 |
5 | MNO | 500 |
1 | JKL | 600 |
In other words, create some sort of ranking query based on the existing SortOrder values, then update the SortOrder values based on that ranking
Here's my ranking query :
Code:
SELECT T1.ID, T1.SortOrder, (SELECT Count(*) FROM tbl AS T2 WHERE T2.SortOrder <= T1.SortOrder ) AS Rank
FROM tbl T1
But I can't perform the update with this as a sub-query...
Code:
UPDATE tbl T
INNER JOIN
(SELECT T1.ID, (SELECT Count(*) FROM tbl AS T2 WHERE T2.SortOrder <= T1.SortOrder ) AS Rank
FROM tbl T1) R ON T.ID = R.ID
SET T.SortOrder = R.Rank * 100
...as :
"Operation must use an updateable query"
Any suggestions as to how I might go about this? Preferably as efficiently as possible; the tables are relatively small but I'd like something nice and quick that I can just fire whenever a new record is added or an existing record deleted (or, an existing record is updated with a different SortOrder) to keep that field nice and neat?
Thanks
AOB