开发者

sql server: recursive stored procedure

开发者 https://www.devze.com 2023-01-05 08:42 出处:网络
I have a very generic set of three tables that store all of my data, which works brilliantly (we are talking small quantities of data here)

I have a very generic set of three tables that store all of my data, which works brilliantly (we are talking small quantities of data here)

DataContainer - Manages 'records'

PK - DataContainerId
FK - ParentDataContainerId
FM - ModelEntityId

DataInstance - Manages versioning

PK - DataInstanceId
FK - DataContainerId
     IsCurrent [bit] NOT NULL CONSTRAINT [DF_DataInstance_IsCurrent]  DEFAULT ((1)),
     ModifiedBy [nvarchar](50) NOT NULL CONSTRAINT [DF_DataInstance_ModifiedBy]  DEFAULT (suser_sname()),
     ModifiedDateTime [datetime] NOT NULL CONSTRAINT [DF_DataInstance_ModifiedDateTime]  DEFAULT (getdate()),

DataValue

PK - DataValueId
FK - DataInstanceId
FK - ModelEntityId
     ValueText --the actual values 

Problem: When a record is deleted I need to flag all child records for deletion.

Attempt

--flag current record as deleted
update DataInstance 
set IsCurrent = 0
Where DataContainerId = @DataContainerId
And (@ModelContainerId is null or @ModelContainerId = ModelContainerId)

--remove all child records
declare db_cursor for
select sc.DataContainerId as 'ChildDataContainerId' from DataInstance di
inner join datacontainer dc on dc.datacontainerId = di.datacontainerId
where parentdatacontainerId = @DataContainerId

declare @ChildDataContainerId int
open db_cursor
fetch next from db_cursor into @ChildDataContainerId开发者_StackOverflow

while @@fetch_status = 0
begin
  exec dataInstance_Delete null, @ChildDataContainerId --current sp
end

close db_cursor
deallocate db_cursor

The problem is that I cant use cursors recursivly (as I get an error that the cursor is already open), so this SP will only work one level deep.

Is there a more cunning way to do this?


As Tahbaza suggested, it was a fairly simple trigger,

create trigger DataInstance_Trigger
    On DataInstance
After update
as
Begin
    Update
        DataInstance
    Set
        DataInstance.IsCurrent = 0
    From DataInstance di, Inserted i
    Inner join DataContainer dc on
       i.DataContainerId = dc.ParentDataContainerId
    Where di.DataContainerId = dc.DataContainerId
          di.IsCurrent = 1

End

0

精彩评论

暂无评论...
验证码 换一张
取 消