I want to create stored procedure that call recursion function, each time it will execute update statement.
I have a table called document
documentId folderId
---------- --------
1222 1
1256 2
1257 3
And a folder table:
folderId parentFolder
-------- -----------
1 5
2 1
3 2
5 null
My stored procedure will delete folder number (1), when it has been deleted, it should move all document in folder 1 and sub folder of 1 to the parent folder of 1.
How to do that?
CREATE FUNCTION fn_deleteSubFolderDocument
(
@folderId INT ,
@newFolderId INT
)
RETURNS NVARCHAR(100)
AS
BEGIN
DECLARE @count2 int
SET @count2=(SELECT COUNT(*) FROM dbo.tbl_document_folder WHERE parent_folder=@folderId)
UPDATE tbl_document SET folder_id=@newFolderId WHERE folder_id=@folderId
IF(@count2 !=0)
BEGIN
DECLARE @table TABLE(id INT IDENTITY(1,1),folderId INT,parentFolder int )
INSERT INTO @table(folderId,parentFolder)
SELECT folder_id,parent_folder FROM dbo.tbl_document_folder WHERE parent_folder=folder_id
DECLARE @index INT =0
WHILE @index<@count2
BEGIN
SET @index=@index+1
RETURN fn_deleteSubFolderDocument((SELECT folderId FROM @table WHERE id=@index),(SELECT parentFolder FROM @table WHERE id=@index ))
END
END
END
GO
I’m trying to replicate in SQLfiddle to try to walk down through the tree of dependencies you’ve illustrated as I think your problem is similar to this SO Answer
ok – this will walk down your tree for you:
Here is the recirsive CTE that walks down the tree and finds the subfolders of subfolders of subfolders …
I’ve saved a live example here on SQLfiddle
Once you have this set of folders it should be easy enough to find all the associated documents that you need to move
Referring to this article by Pinal Dave I’ve amended the way the loop detects it’s maximum. Without any sort of catch for the maximum if the loop carried on past 100 iterations the server would error but according to this article it looks like MAXRECURSION can be set as high as 32767….hopefully your file structure isn’t that complex!