简体   繁体   English

在联接中使用表值函数

[英]Using Table valued Function in join

There is a Table valued function which gives multiple rows as output and there are 2 columns as output. 有一个表值函数,该函数给出多行作为输出,有2列作为输出。

Now I want use this function in the query for all the employees in the employees table 现在,我想在查询中使用此函数为employees表中的所有employee

I am using CROSS APPLY but its taking long time and doesn't give any result. 我正在使用CROSS APPLY,但是它花费了很长时间,并且没有得到任何结果。

This is the query which I tried 这是我尝试过的查询

select *
from emp A Cross APPLY fnempDiv(A.EmpID)

I am using CROSS APPLY 我正在使用CROSS APPLY

  • its taking long time 需要很长时间

Unfortunately, that's the nature of CROSS APPLY, since it is a row-by-row operator. 不幸的是,这是CROSS APPLY的本质,因为它是逐行运算符。 It works great for a few employee rows (convenient) but from what you describe, you should avoid it for this query and expand the query in the APPLY to the outer query. 它非常适合一些员工行(方便),但从您的描述来看,对于此查询,应避免使用它,并将APPLY中的查询扩展到外部查询。 A simple INNER JOIN should do. 一个简单的INNER JOIN应该可以。

  • doesn't give any result. 没有任何结果。

CROSS APPLY removes emp A records that don't produce any rows from the APPLY. CROSS APPLY从APPLY中删除不产生任何行的emp A记录。 OUTER APPLY will keep the emp A records. OUTER APPLY将保留emp A记录。 If you are getting 0 records overall, you might have passed the wrong column, eg A.EmpID is not the correct key. 如果总体上获得0条记录,则可能是传递了错误的列,例如A.EmpID不是正确的键。

If the function is defined like this (from your comment): 如果函数是这样定义的(根据您的评论):

CREATE FUNCTION dbo.fnempDiv(@EmpID)
RETURNS TABLE AS RETURN
 SELECT A.EmpID,D.Name
 FROM empdetail A
 INNER JOIN empdiv D on A.empID=D.ID
 where EXISTS (select * from X)
GO

It makes no sense at all. 这根本没有意义。 Select * from X either fails the entire query or becomes a dud condition, simply by having a record in X or otherwise. Select * from X或是发生故障,整个查询或成为哑弹的条件,只需通过在创纪录的X或以其他方式。 The input parameter @EmpID is also not being used. 也未使用输入参数@EmpID

On the other hand, if it is declared as follows: 另一方面,如果声明如下:

CREATE FUNCTION dbo.fnempDiv(@EmpID)
RETURNS TABLE AS RETURN
 SELECT A.EmpID,D.Name
 FROM empdetail A
 INNER JOIN empdiv D on A.empID=D.ID
 where A.EmpID = @EmpID
GO

Then your full query can be rewritten 然后,您的完整查询可以被重写

select E.*, A.emp_ID as EmpDetail_Emp_ID, D.Name
from emp E
INNER JOIN empdetail A ON E.emp_ID=A.EMP_ID
INNER JOIN empdiv D on A.empID=D.ID

Moreover, the join A.empID=D.ID doesn't even look right. 此外,连接A.empID=D.ID甚至看起来都不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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