Ecco quello che ho come VBScript sottoprogrammi:È possibile che una stored procedure venga chiamata in modo ricorsivo in SQL Server?
sub buildChildAdminStringHierarchical(byval pAdminID, byref adminString)
set rsx = conn.execute ("select admin_id from administrator_owners where admin_id not in (" & adminString & ") and owner_id = " & pAdminID)
do while not rsx.eof
adminString = adminString & "," & rsx(0)
call buildChildAdminStringHierarchical(rsx(0),adminString)
rsx.movenext
loop
end sub
Esiste un modo per trasformare questo in una stored procedure dal momento che è ricevuto la chiamata ricorsiva nella subroutine?
Ecco che cosa ho provato ...
CREATE PROCEDURE usp_build_child_admin_string_hierarchically
@ID AS INT,
@ADMIN_STRING AS VARCHAR(8000),
@ID_STRING AS VARCHAR(8000) OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @index int;
DECLARE @length int;
DECLARE @admin_id int;
DECLARE @new_string varchar(8000);
SET @index = 1;
SET @length = 0;
SET @new_string = @ADMIN_STRING;
CREATE TABLE #Temp (ID int)
WHILE @index <= LEN(@new_string)
BEGIN
IF CHARINDEX(',', @new_string, @index) = 0
SELECT @length = (LEN(@new_string) + 1) - @index;
ELSE
SELECT @length = (CHARINDEX(',', @new_string, @index) - @index);
SELECT @admin_id = CONVERT(INT,SUBSTRING(@new_string, @index, @length));
SET @index = @index + @length + 1;
INSERT INTO #temp VALUES(@admin_id);
END
DECLARE TableCursor CURSOR FOR
SELECT Admin_ID FROM Administrator_Owners WHERE Admin_ID NOT IN (SELECT ID FROM #temp) AND Owner_ID = @ID;
OPEN TableCursor;
FETCH NEXT FROM TableCursor INTO @admin_id;
WHILE @@FETCH_STATUS = 0
BEGIN
IF LEN(@ID_STRING) > 0
SET @ID_STRING = @ID_STRING + ',' + CONVERT(VARCHAR, @admin_id);
ELSE
SET @ID_STRING = CONVERT(VARCHAR, @admin_id);
EXEC usp_build_child_admin_string_hierarchically @admin_id, @ID_STRING, @ID_STRING;
FETCH NEXT FROM TableCursor INTO @admin_id;
END
CLOSE TableCursor;
DEALLOCATE TableCursor;
DROP TABLE #temp;
END
GO
ma ottengo il seguente errore quando che stored procedure viene chiamata ... Un cursore con lo stesso nome 'TableCursor' esiste già.
Suppongo che l'errore si verifichi perché la chiamata ricorsiva viene eseguita prima che il cursore "TableCursor" sia chiuso. Sarebbe possibile dare al cursore un nome dinamico (forse 'TableCursorN', dove N è la profondità della ricorsione - dovresti farlo come parametro extra)? – FrustratedWithFormsDesigner
Il problema non è la ricorsione, che è certamente consentita (http://msdn.microsoft.com/en-us/library/aa175801(SQL.80).aspx), è che stai usando un nome di cursore statico. Non ne so abbastanza sui cursori in MS SQL Server per postare questo come una risposta, però, dal momento che * dovrebbe * dire come utilizzare un cursore in questa situazione per essere utile! :-) –