简体   繁体   中英

Joining with Table Valued Function

The UDF(my_udf) I am working on takes JobId as a parameter and returns a table of different candidates(Candidate Id) and their corresponding scores that have applied to the job.

Now I want to display list of all candidates, job they have applied and the corresponding score. So my query is something like this:

select * from JobANDCandidates jc inner join Candidates c ON jc.candidateId = c.Id inner join Jobs j on j.Id = jc.jobId Cross apply my_udf(jc.JobId)

But above query takes too much time and is incorrect.

I somehow need to cross apply only to the row returned from UDF based on the candidate ID. I tried CROSS APPLY my_udf(jc.JobId) fun ON/WHERE fun.candidateId = c.Id , but neither ON clause or WHERE clause works. I get compile error.

Please help

This should work:

select . . . 
from JobANDCandidates jc inner join
     Candidates c 
     on jc.candidateId = c.Id inner join
     Jobs j
     on j.Id = jc.jobId Cross apply
     dbo.my_udf(jc.JobId) f
where c.id = f.candidateid

This assumes that the TVF has a column called candidateid . Otherwise, you might have to specify that with the alias f(candidateid, . . .) .

Note: This may not have a significant impact on performance, because the query still needs to process the entire TVF. You might want to allow the function to take a candidate id as an argument.

I would suggest refactoring the UDF as a simple view, and JOINing to that. Indexes will be applied with the view, so speed should be very good.

IMHO, a UDF is overkill for this type of operation when a normal view can be used, especially if there is ever any concern for portability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM