Inline Table Valued Function in SQL Server 2005

Do you remember VIEW? VIEW used to wrap up the SELECT statement in SQL Server. Inline Table Valued Function is the same as VIEW which has all features of VIEW along with compilation feature of stored procedure and parameter facility. You can use this function in JOIN also. When you call function first time, it compiles and stores the plan so that sub-sequent calls to same function boost up the speed.

Let me show you one example of this cool tool of Microsoft SQL Server.

–create one table for demo

use adventureworks

CREATE TABLE emps

(

Name VARCHAR(50),

Dept VARCHAR(10),

Company VARCHAR(15)

)

–INSERT records

INSERT INTO emps

SELECT ‘Ritesh’,‘MIS’,‘echem’ UNION ALL

SELECT ‘Bihag’, ‘MIS’, ‘CT’ UNION ALL

SELECT ‘Rajan’, ‘account’,‘Marwadi’ UNION ALL

SELECT ‘Alka’,‘account’,‘tata’ UNION ALL

SELECT ‘Alpesh’,‘Chemical’,‘echem’

GO

–creating inline table valued function

CREATE FUNCTION dbo.GetEmployeeData(@dept VARCHAR(10))

RETURNS TABLE

AS

RETURN

(

SELECT * FROM emps WHERE dept=@dept

)

GO

–check whether function works

SELECT Name,Company FROM dbo.GetEmployeeData(‘MIS’)
GO

Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of http://www.SQLHub.com

Microsoft SQL Server Blog. Fight the fear of SQL with SQLHub.com. Founder is Ritesh Shah

One thought on “Inline Table Valued Function in SQL Server 2005

Comments are closed.