0
CREATE VIEW View1 
    AS 
    SELECT Col1, 
     Col2, 
     dbo.fn1(col2) as Col3 
    FROM TestTable 

    /* 
    --Instead of writing below query I created a new View View2 


    SELECT Col1, 
     Col2, 
     dbo.fn1(col2) as Col3 
     dbo.fn2(dbo.fn1(col2)) as Col4 
    FROM TestTable 
    */ 

    CREATE VIEW View2 
    AS 
    SELECT Col1, 
     Col2, 
     Col3, 
     dbo.fn3(col3) as Col4 
    FROM TestTable 

我有類似上面的查詢。我有一列是fn1的輸出。我想將該輸出用於其他函數fn2。在這種情況下,我不能直接在fn2中使用col3,所以我分割了兩個函數和視圖,如下所示。我想知道我正朝着正確的方向發展,我正在做的是正確的還是有更好的方法來做到這一點?在View1的註釋部分將函數fn1調用兩次?或者SQL Server會照顧優化呢?SQL Select語句中的函數

回答

0

您coudl做到這一點...

SELECT 
    Col1, 
    Col2, 
    col3, 
    dbo.fn2(col3) AS Col4 
FROM 
    (
    SELECT 
     Col1, 
     Col2, 
     dbo.fn1(col2) as Col3 
    FROM 
     TestTable 
    ) foo