Thursday, October 13, 2011

Inline Table Valued Function

/* Code : Create an Inline Table Valued Function */
CREATE FUNCTION dbo.MyFn_CustomerNamesInRegion()
RETURNS table
AS
RETURN (
        SELECT DISTINCT *
        FROM dbo.DimEmployee
       );
/* Call Above Function */
SELECT *
FROM dbo.MyFn_CustomerNamesInRegion()


- Inline Function Rule
  • The RETURN clause contains a single statement in parentheses. Creating a function like below would result in "FAILURE" since it has more than one statement in the return clause :
    CREATE FUNCTION dbo.MyFn_CustomerNamesInRegion()
    RETURNS table
    AS
    RETURN (
            INSERT INTO dbo.temp2(column2)
    SELECT * 
    FROM dbo.DimEmployee
           );

  • The result set of the SELECT statement forms the table returned by the function. The SELECT statement used in an inline function is subject to the same restrictions as SELECT statements used in views.
  • There is no function_body delimited by BEGIN and END.
  • The table-valued function accepts only constants or @local_variable arguments.