Search code examples
sql-server-2012table-valued-parameters

Inline function versus normal select


Now I am studying about functions in SQL Server 2012. I knew that there are three function types. But I am confused by Inline Table-Value Functions.

Let me explain.

select * into Number 
from (
 values 
  (1, 'A'),(2, 'B'),(3, 'C')
) number (N, C)

create function InlineFun (@i int)
returns table
as
return (select * from Number where n = @i)

select * from Number where n = 1
select * from InlineFun (1)

From the above select's the results are the same. Then what is the exact scope of Inline TVF..?

Note :

I am using Microsoft SQL Server 2012


Solution

  • Think of an ITVF as a view you can pass parameters to. It is essentially included in your script that references it as if it was plain old SQL and then executed. This is why they perform better than multi statement table valued functions, which have to be executed as a seperate statement.

    Due to this, in your examples the statement:

    select *
    from InlineFun (1)
    

    Is essentially passed to the query engine as:

    select *
    from (select *
          from Number
          where n = 1
         ) as a
    

    So to actually answer your question, the scope of the function is the same as the scope of the statement that calls it.