如何在视图中重用计算字段的结果

时间:2013-09-19 08:56:33

标签: sql stored-procedures view

我有一个像这样的观点:

CREATE VIEW [dbo].[myview] AS
SELECT   
       dbo.table1.field1
      ,dbo.table2.field2  
      ,dbo.HeavyStoredProcedure(dbo.table1.field1) AS calculated_value 
      ...
FROM
      table1
      INNER JOIN table2 ON (...)
WHERE  
      ...
      AND NOT( EXISTS (SELECT * from table3 
               WHERE (table3.somefield = dbo.HeavyStoredProcedure(dbo.table1.field1)))
               OR
               EXISTS (SELECT * from table4
               WHERE (table4.anotherfield = dbo.HeavyStoredProcedure(dbo.table1.field1)))
             )

这里的问题是“HeavyStoredProcedure”完全相同的参数多次调用,从而减慢了整个过程的速度。

如何在view1中每行调用“HeavyStoredProcedure”一次,然后在WHERE子句中重复使用计算结果两次?

1 个答案:

答案 0 :(得分:0)

对于SQL Server,请尝试:

CREATE VIEW [dbo].[myview] AS
SELECT   
       dbo.table1.field1
      ,dbo.table2.field2  
      ,
      ...
FROM
      table1
      INNER JOIN table2 ON (...)
      outer apply (
          select dbo.HeavyStoredProcedure(dbo.table1.field1) AS calculated_value 
      ) as CALC
WHERE  
      ...
      AND NOT( EXISTS (SELECT * from table3 
               WHERE (table3.somefield = CALC.calculated_value))
               OR
               EXISTS (SELECT * from table4
               WHERE (table4.anotherfield = CALC.calculated_value))
             )