开发者

Joining 3 fast udfs to make one slow query

I'm trying to make a select statement that joins results from three in-line table functions (SQL Server 2005). The first two functions join as follows:

    SELECT Client_no
       ,Portfolio_no
       ,Sum(Nominal * Price) AS Value
FROM   Dbo.Udf_bulkportfolioholdings (@TradeDate) AS Holdings
       INNER JOIN Dbo.Udf_bulkpricesecurities (@TradeDate) AS Prices ON Prices.Security_no = Holdings.Security_no
GROUP  BY Client_no
          ,Portfolio_no

This query takes approx 0.7 secs to run.

The third function is queried alone as follows and takes 0.006 secs to run:

SELECT Currencyid
         ,Currencycode
         ,Multiexchangerate
  FROM   Dbo.Udf_bulkexchangerates(@TradeDateint)

So joining some really fast queries together should make one fast query, right?

SELECT Client_no
       ,Portfolio_no
       ,Sum(Nominal * Price * Multiexchangerate) AS Value
FROM   Dbo.Udf_bulkportfolioholdings (@TradeDate) AS Holdings
       INNER JOIN Dbo.Udf_bulkpricesecurities (@TradeDate) AS Prices ON Prices.Security_no = Holdings.Security_no
       INNER JOIN Dbo.Udf_bulkexchangerates(@TradeDateint) AS Fx ON Fx.Currencycode =开发者_如何学编程 Prices.Currency
GROUP  BY Client_no
          ,Portfolio_no

Join the third function into the query and it takes 40+ seconds!

I've double checked the fields in the joins and they're the correct fields. I would have thought/hoped that the query optimizer looks at the three functions and gets all three tables first, then joins them together. But it looks like it's running the third query for each record returned?

I've tried returning the exchangerates first into a table variable and that takes execution time down to 9 seconds but this seems messy. Is there any way to force the optimizer to run the three tables first, then join?

Any help would be greatly appreciated.


Well, you actually try this: first join the 2 tables and then join the resulting derived table to the exchangerates udf. That would probably make the optimizer work the way you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜