Inline Table Valued Function in SQL Server 2005

Sunday, March 22, 2009 |

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

1 comments:

Pravesh Singh said...

This is best one article so far I have read online. I would like to appreciate you for making it very simple and easy. I have found another nice post related to this post over the internet which also explained very well. For more details please check out this link...

Table-Valued function in SQL server


Thanks