Таблица:
NormCatalogID pk
Name varchar
RefID - ссылка на NormCatalogID parent'а
Lk - левый ключ
Rk - правый ключ
Lev - уровень
- Код: Выделить всё
ALTER proc [dbo].[procMoveNormCtlg]
@NormCatalogID int,
@ParentID int
as
begin tran
declare @Lev int, @Lk int, @Rk int
declare @LevNew int, @right_key_near int, @PrevID int
declare @skew_level int, @skew_tree int, @skew_edit int
SELECT @Lev = Lev, @Lk = Lk, @Rk = Rk FROM tblNormCatalog WHERE NormCatalogID = @NormCatalogID
select @LevNew = Lev, @right_key_near=Rk-1 FROM tblNormCatalog WHERE NormCatalogID = @ParentID
set @skew_level = @LevNew - @Lev + 1
set @skew_tree = @Rk - @Lk + 1
set @skew_edit = @right_key_near - @Lk + 1
print @right_key_near
print @Rk
if @right_key_near>@rk
UPDATE tblNormCatalog
SET Lk = case when Rk <= @Rk then Lk + @skew_edit else case when Lk > @Rk then Lk - @skew_tree else Lk end end,
Lev = case when Rk <= @Rk then Lev + @skew_level else Lev end,
Rk = case when Rk <= @Rk then Rk + @skew_edit else case when Rk <= @right_key_near then Rk - @skew_tree else Rk end end
WHERE Rk > @Lk AND
Lk <= @right_key_near
else
UPDATE tblNormCatalog
SET Rk = case when Lk >= @Lk then Rk + @skew_edit else case when Rk < @Lk then Rk + @skew_tree else Rk end end,
Lev = case when Lk >= @Lk then Lev + @skew_level else Lev end,
Lk = case when Lk >= @Lk then Lk + @skew_edit else case when Lk > @right_key_near then Lk + @skew_tree else Lk end end
WHERE Rk > @right_key_near AND Lk < @Rk
update tblNormCatalog Set RefID = @ParentID where NormCatalogID = @NormCatalogID
if @@error<>0
rollback tran
else
commit tran