I have a function that I use to compute the number of days that a patient is unavailable in order to reduce the number of days they have breached a waiting times deadline.The function is as follows:[code="sql"]CREATE FUNCTION [dbo].[GetDaysUnavailable] ( @intRef int)RETURNS intASBEGIN DECLARE @ReturnValue int DECLARE @dtUnavailFrom datetime DECLARE @dtUnavailTo datetime DECLARE @dtRefRcvd datetime SELECT @dtUnavailFrom = UnavailableFrom FROM Referrals WHERE ReferralID = @intRef SELECT @dtUnavailTo = UnavailableTo FROM Referrals WHERE ReferralID = @intRef SELECT @dtRefRcvd = ReferralReceivedDate FROM Referrals WHERE ReferralID = @intRef IF ISNULL(@dtUnavailFrom,'') = '' OR ISNULL(@dtUnavailTo,'') = '' BEGIN SELECT @ReturnValue = 0 END ELSE BEGIN IF @dtRefRcvd > @dtUnavailFrom BEGIN SELECT @ReturnValue = DATEDIFF(day,@dtRefRcvd, @dtUnavailTo) END ELSE BEGIN SELECT @ReturnValue = DATEDIFF(day,@dtUnavailFrom, @dtUnavailTo) END END RETURN @ReturnValueEND[/code]As you can see it works out the difference between the date that the person is unavailable to and either the date they are unavailable from or the date their referral was received. This was fine using my original structure whereby the 2 date fields were in the main table. The problem with this was that there could only ever be 1 period of unavailability.I have now changed the table structure so that the unavailability periods are in their own table which has a 1-to-many relationship with the main table.But now I can't figure out how to get my function to cope withe new structure. I basically need to be able to pull every row in the unavailability table that relates to the parent record and them loop through each row, summing up the unavailability and returning the total at the end.Any ideas?
↧