我想创建调用递归函数的存储过程,每次它都会执行更新语句。
我有一张桌子叫document
documentId folderId
---------- --------
1222 1
1256 2
1257 3
还有一张folder
桌子:
folderId parentFolder
-------- -----------
1 5
2 1
3 2
5 null
我的存储过程将删除文件夹号(1),当它被删除时,它应该将文件夹1和1的子文件夹中的所有文档移动到1的父文件夹。
怎么做?
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