I am creating a list to send an e-mail to. The individual who is logged in has a field in the database of who they report to (unless there is an error or they report to no one).
So for instance if I am logged in and clicked the submit button in SQL it would say I report to 'John Doe'
I then need to grab who 'John Doe' reports to and add that to the list. I need to keep climbing the list until we reach the top of the company (the GID will be blank or null).
Using me as an example, I report to 'John Doe' who reports to 'Tom Doe'. Tom reports to no-one his usrReportsTo field is like this '00000000-0000-0000-0000-000000000000'.
If the usrReportsTo field is "" or NULL or '00000000-0000-0000-0000-000000000000' the loop should terminate.
Here is the sql I used.
What is the cleanest/neatest/most effecient way to perform this loop and is it better to do it in SQL or ASP.net C#?
select usrReportsTo from dbo.CVT_Users_usr, usrEmailAddress
WHERE RTRIM(usrFirstName) + ' ' + RTRIM(usrLastName) = 'James Wilson'
-- Returns 'James Wilson' + email
SELECT RTRIM(usrFirstName) + ' ' + RTRIM(usrLastName) as Name, usrEmailAddress, usrReportsTo from dbo.CVT_Users_usr
WHERE usrGID = '38922F83-4B6E-499E-BF4F-EF0B094F47F7'
-- Returns 'John Doe' + email + reportsTo
SELECT RTRIM(usrFirstName) + ' ' + RTRIM(usrLastName) as Name, usrEmailAddress, usrReportsTo from dbo.CVT_Users_usr
WHERE usrGID = 'FB8F4939-3956-4834-9D89-D72AFB8BF3E0'
-- Returns 'Tom Doe' + email + reportsTo
Edit #3
Working copy of SQL just doesn't return 100% true data.
with cte AS ( select usrGID, RTRIM(usrFirstName) + ' ' + RTRIM(usrLastName) as Name, usrEmailAddress, usrReportsTo from dbo.CVT_Users_usr union all select u.usrGID, RTRIM(u.usrFirstName) + ' ' + RTRIM(u.usrLastName), cte.usrEmailAddress, cte.usrReportsTo from dbo.CVT_Users_usr u inner join cte on u.usrReportsTo = cte.usrGID ) select * from cte where Name = 'James Wilson'
-- Returns
usrGID Name usrEmailAddress usrReportsTo E1DAFC11-BE35-4730-9961-68EEF8D85DE4 James Wilson 38922F83-4B6E-499E-BF4F-EF0B094F47F7 E1DAFC11-BE35-4730-9961-68EEF8D85DE4 James Wilson [email protected] FB8F4939-3956-4834-9D89-D72AFB8BF3E0 E1DAFC11-BE35-4730-9961-68EEF8D85DE4 James Wilson [email protected] 00000000-0000-0000-0000-000000000000
Shouldn't the usrGID and name match the same way usrEmailAddress and usrReportsTo does? I tried chaanging the sql to be cte.USRGID and cte.Name but it gave the max recursion error.
Any ideas?