0

I have the following database design:

Table Content
ID     Status     ReplacedId

1   C       NULL
2   C       1
3   C       2
4   A       3
5   A       NULL
6   A       NULL
7   A       NULL

the logic here is as follows

Id "1" is Canceled and instead that ID "2" is created so the Record 2 has a reference to the ID "1" in the ReplacedId column. like that iD 2 is canceled and Id "3" is created , "3" is canceled and "4" is created. the canceled records status is "C" and the Active records Status is "A"

My Requirement :

i have to show the Active record for the Id by passing the Id (1) if that is a canceled record othere wise the same record if that is a active record.

4

1 回答 1

0
DECLARE @Table TABLE(
        RecordID INT,
        Status VARCHAR(20),
        ParentID INT
)

INSERT INTO @Table SELECT     1,'C',NULL
INSERT INTO @Table SELECT     2,'C',1
INSERT INTO @Table SELECT     3,'C',2
INSERT INTO @Table SELECT     4,'A',3
INSERT INTO @Table SELECT     5,'A',NULL
INSERT INTO @Table SELECT     6,'A',NULL

DECLARE @RecordID INT

SELECT @RecordID = 1

;WITH Selects AS (
        SELECT *
        FROM    @Table
        WHERE   RecordID = @RecordID
        UNION ALL
        SELECT  t.*
        FROM    @Table t INNER JOIN
                Selects s ON t.ParentID = s.RecordID
)
SELECT  *
FROm    Selects where Status = 'A'
于 2013-08-26T07:28:26.543 回答