views:

90

answers:

1
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

I have a query like above. I have column that is an output of fn1. I wanted to use that output to other function fn2. In that case I cannot the use the col3 directly in fn2 so I have split two function and view as below . I wanted to know am I moving in the right direction, is it right what I am doing or is there a better way to do it ?. In the commented part of the View1 will the function fn1 called twice ? or SQL Server will take care of the optimizing it ?

A: 

You coudl do this...

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