How to write a recursive query in SQL Server 2000

柔情痞子 提交于 2019-12-04 23:17:58

Let's break it down.

Firstly, a UDF to get the next 'value'

CREATE FUNCTION dbo.GetNextReference
(
    @CurrentRef varchar(25)
)
RETURNS varchar(25)
AS
BEGIN
    DECLARE @NextRef varchar(25)
    SELECT @NextRef = [References]
    FROM R
    WHERE '(' + [Name] + ',' + [LineNo] + ')' = @CurrentRef

    RETURN @NextRef
END

Next one to find the final value for each entry :

CREATE FUNCTION dbo.GetFinalReference
(
    @StartRef varchar(25)
)
RETURNS varchar(25)
AS
BEGIN
    DECLARE @NextRef varchar(25), @CurrentRef varchar(25)
    SELECT @NextRef = dbo.GetNextReference(@StartRef), @CurrentRef = @StartRef
    WHILE @NextRef is not null
    BEGIN
        SET @CurrentRef = @NextRef
        SET @NextRef = dbo.GetNextReference(@CurrentRef)
    END

    --at this point @NextRef will be null, so we look in the other table
    DECLARE @FinalValue varchar(25)
    SELECT @FinalValue = [Values]
    FROM GeneratedValues
    WHERE '(' + [Name] + ',' + [LineNo] + ')' = @CurrentRef

    RETURN @FinalValue
END

Finally, we can run a SELECT

SELECT [Name], [LineNo], dbo.GetFinalReference([References]) AS [Values]
FROM R

I hope this is all clear, and I haven't made any syntactical errors. The use of UDFs may mean this query won't run as quick as you'd like, but I think the UDFs will be useful to you in any case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!