Sesuatu seperti ini mungkin membantu:
Pertama beberapa data uji:
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)
Kuerinya seperti ini:
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
Untuk mendapatkan output yang diinginkan, Anda tidak perlu menggunakan seniorDoctorId
karena mereka sudah memiliki hubungan orang tua anak.
Lihat contoh di sini