When adding an item in my database, I need it to auto-determine the value for the field DisplayOrder. Identity (auto-increment) would be an ideal solution, but I need to be able to programmatically change (UPDATE) the values of the DisplayOrder column, and Identity doesn’t seem to allow that. For the moment, I use this code:
CREATE PROCEDURE [dbo].[AddItem]
AS
DECLARE @DisplayOrder INT
SET @DisplayOrder = (SELECT MAX(DisplayOrder) FROM [dbo].[MyTable]) + 1
INSERT INTO [dbo].[MyTable] ( DisplayOrder ) VALUES ( @DisplayOrder )
Is it the good way to do it or is there a better/simpler way?
A solution to this issue from “Inside Microsoft SQL Server 2008: T-SQL Querying”
Or another alternative from the same book that allocates ranges easier. (You would need to consider whether to call this from inside or outside your transaction – inside would block other concurrent transactions until the first one commits)