Declare @editTableName varchar(50)--表名
Declare @mainFieldName varchar(50)--主键字段名称
Declare @fjIdFieldName varchar(50)--上级字段名称
Declare @sortFieldName varchar(50)--排序字段名称
Declare @updatedString nvarchar(max)
Declare @updateString1 varchar(4000)
Declare @updateString2 varchar(4000)
Select @editTableName='SystemClass'
Select @mainFieldName='Id'
Select @fjIdFieldName='ParentId'
Select @sortFieldName='SortNumber'
Select @updateString1='(Select t1.['+@mainFieldName+'],ROW_NUMBER() OVER(ORDER BY t1.['+@sortFieldName+'] Asc,t1.['+@mainFieldName+'] ASC) as newSortNumber from ['+@editTableName+'] t1 where t1.['+@fjIdFieldName+']=['+@editTableName+'].['+@fjIdFieldName+']) o1'
Select @updateString2='Select top 1 o1.newSortNumber From '+@updateString1+' Where o1.['+@mainFieldName+']=['+@editTableName+'].['+@mainFieldName+']'
Select @updatedString='Update ['+@editTableName+'] Set ['+@sortFieldName+']=IsNull(('+@updateString2+'),1)'
Exec(@updatedString)