Question

Consider the following sql query:

SELECT TaskId,FromItemId, IHV_FROM.NodePath as FromPath
FROM VIEW_TASKS with (nolock) 
left Join fn_ITEM_HIERARCHY(FromItemId) IHV_FROM ON FromItemId = IHV_FROM.ItemId
WHERE ...

fn_ITEM_HIERARCHY is a function which takes one input parameter. I would like to use FromItemId from VIEW_TASKS as input parameter to the function. When doing it like above, i get the error (Microsoft SQL Server 2008) "Invalid column name".

The SELECT statement returns multiple values, so it is not possible to assign the value to a variable in a separate select statement. Any ideas?

Was it helpful?

Solution

You probably need to use OUTER APPLY in this case:

SELECT TaskId,FromItemId, IHV_FROM.NodePath as FromPath
FROM VIEW_TASKS with (nolock) 
OUTER APPLY fn_ITEM_HIERARCHY(FromItemId) IHV_FROM
WHERE ...
;

If the function always returns rows or if you only want results for values where the function does return rows, use CROSS APPLY instead.

OTHER TIPS

use alias

SELECT t.TaskId, t.FromItemId, IHV_FROM.NodePath as FromPath
FROM VIEW_TASKS t with (nolock) 
left Join fn_ITEM_HIERARCHY(FromItemId) IHV_FROM ON t.FromItemId = IHV_FROM.ItemId

use OUTER APPLY instead of left join

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top