我正在创建一个有两列的表,我想自动递增.一列是主键,所以我在其上使用IDENTITY关键字.另一列将用于跟踪表中项目的用户定义的“排序顺序”.任何时候,用户移动一个项目,它的“排序顺序”将与另一个元素的值交换值.但是,当一个项目插入到表中时,插入的项目应始终自动分配比表中任何其他值高的排序顺序值.以下是表创建脚本的简化版本:
CREATE TABLE [AnswerRow] ( [AnswerRowId] [int] IDENTITY(1,1) NOT NULL,[SortOrder] [int] NOT NULL,[IsDeleted] [bit] NOT NULL CONSTRAINT [DF_AnswerRow_IsDeleted] DEFAULT 0,CONSTRAINT [PK_AnswerRow] PRIMARY KEY CLUSTERED ([AnswerRowId] asc) )
解决方法
我不知道这是什么@Stephen Wrighton想到的,但是我认为你可以使用一个插入触发器来使用为AnswerRowId生成的IDENTITY值:
CREATE TRIGGER [dbo].[AnswerRowInsertTrigger] ON [dbo].[AnswerRow] AFTER INSERT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; UPDATE a SET a.SortOrder = a.AnswerRowId FROM AnswerRow a JOIN inserted i ON a.AnswerRowId = i.AnswerRowId END