Noget som dette kan måske hjælpe:
Først nogle testdata:
DECLARE @DoctorInfo TABLE
(
doctorId INT,
fistName VARCHAR(100),
seniorDoctorId INT
)
INSERT INTO @DoctorInfo
VALUES
(34,'ABC',0),
(35,'XYZ',34),
(36,'bsd',34),
(37,'dfdf',35),
(38,'dffdg',0)
Forespørgslen sådan her:
DECLARE @doctorId INT
SET @doctorId=35
;WITH CTE(doctorId,seniorDoctorId,fistName)
AS
(
SELECT
DoctorInfo.doctorId,
DoctorInfo.seniorDoctorId,
DoctorInfo.fistName
FROM
@DoctorInfo AS DoctorInfo
WHERE
[email protected]
UNION ALL
SELECT
DoctorInfo.doctorId,
DoctorInfo.seniorDoctorId,
DoctorInfo.fistName
FROM
@DoctorInfo AS DoctorInfo
JOIN CTE
ON DoctorInfo.seniorDoctorId=CTE.doctorId
)
SELECT
*
FROM
CTE
For at få det ønskede output behøver du ikke bruge seniorDoctorId
fordi de allerede har en forældre-barn-relation.
Se eksempel her