How can I force a subquery to perform as well as a #temp table?

后端 未结 4 2088
既然无缘
既然无缘 2020-12-17 08:21

I am re-iterating the question asked by Mongus Pong Why would using a temp table be faster than a nested query? which doesn\'t have an answer that works for me.

Mos

4条回答
  •  醉酒成梦
    2020-12-17 09:03

    Another option (for future readers of this article) is to use a user-defined function. Multi-statement functions (as described in How to Share Data between Stored Procedures) appear to force the SQL Server to materialize the results of your subquery. In addition, they allow you to specify primary keys and indexes on the resulting table to help the query optimizer. This function can then be used in a select statement as part of your view. For example:

    CREATE FUNCTION SalesByStore (@storeid varchar(30))
       RETURNS @t TABLE (title varchar(80) NOT NULL PRIMARY KEY,
                         qty   smallint    NOT NULL)  AS
    BEGIN
       INSERT @t (title, qty)
          SELECT t.title, s.qty
          FROM   sales s
          JOIN   titles t ON t.title_id = s.title_id
          WHERE  s.stor_id = @storeid
       RETURN
    END
    
    CREATE VIEW SalesData As
    SELECT * FROM SalesByStore('6380')
    

提交回复
热议问题