sql server:递归存储过程

时间:2010-06-30 03:19:26

标签: sql-server

我有一组非常通用的三个表来存储我的所有数据,这些数据非常出色(我们在这里讨论的是少量数据)

DataContainer - 管理'记录'

PK - DataContainerId
FK - ParentDataContainerId
FM - ModelEntityId

DataInstance - 管理版本控制

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 

问题:删除记录时,我需要标记所有子记录以进行删除。

尝试

--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

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

close db_cursor
deallocate db_cursor

问题在于我无法递归地使用游标(因为我收到游标已经打开的错误),所以这个SP只能工作一层深度。

有没有更巧妙的方法来做到这一点?

1 个答案:

答案 0 :(得分:0)

正如Tahbaza所说,这是一个相当简单的触发器,

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

结束