Given these two tables:
[dbo].[Task]
[Id] [Duration] [ScheduledStart]
int int Nullable DateTime
[dbo].[TaskDependencies]
[Id] [PredecessorTaskId] [TaskId]
int FK_Task_Id FK_Task_Id
I'm trying to find the latest end date of the Tasks immediate predecessors. For the Task table, ScheduledStart is nullable. The idea behind this is that if it does not have an explicitly scheduled start, it could be derived from its predecessors (the root level tasks must have a ScheduledStart, so the calculation can start somewhere). Tasks can also have multiple predecessors.
I've come up with a fake recursive function that (I think) does what I'm looking for. What I'm wondering is if there is a more efficient way to write this in SQL since I'm used to more procedural programming. Should I just make Function_A a stored procedure and have it call itself? Is there a way this can be accomplished with a WITH statement (and are those a more efficient way of recursive querying, or a recursive function like this)?
DateTime Function_A(Task)
{
var predecessorList = getPredecessors(Task)
var latestEndDate;
var currentPredecessorLatestEndDate;
ForEach(Predecessor in predecessorList)
{
if(Predecessor.ScheduledStart != null)
{
if(latestEndDate != null)
{
if(Predecessor.StartDate + Predecessor.Duration > latestEndDate)
{
latestEndDate = Predecessor.StartDate + Predecessor.Duration;
}
}
else
{
latestEndDate = Predecessor.StartDate + Predecessor.Duration;
}
}
else
{
currentPredecessorLatestEndDate = Function_A(Predecessor.Id);
if(latestEndDate != null)
{
if(currentPredecessorEndDate > latestEndDate)
{
latestEndDate = currentPredecessorEndDate;
}
}
else
{
latestEndDate = currentPredecessorEndDate;
}
}
}
return latestEndDate;
}
Thanks for the help!