I want to know how to create a simple table-valued function in SQL Server.
Thank you.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Lajapathy ArunPosted Apr 30, 2012, 3:45 AM
MuthuMari MPosted Apr 30, 2012, 1:09 AM
An inline table-valued function returns a variable of data type table whose value is derived from a single SELECT statement. Since the return value is derived from the SELECT statement, there is no BEGIN/END block needed in the CREATE FUNCTION statement. There is also no need to specify the table variable name (or column definitions for the table variable) because the structure of the returned value is generated from the columns that compose the SELECT statement. Because the results are a function of the columns referenced in the SELECT, no duplicate column names are allowed and all derived columns must have an associated alias.
The following uses the Customer table in the Northwind database to show how an inline table-valued function is implemented.
USE Northwind go CREATE FUNCTION fx_Customers_ByCity ( @City nvarchar(15) ) RETURNS table AS RETURN ( SELECT CompanyName FROM Customers WHERE City =@City ) go SELECT * FROM fx_Customers_ByCity('London') CompanyName ---------------------------------------- Around the Horn . . . Seven Seas Imports
If this post is useful then mark it as "Accepted Answer"pls refer this url for more details
http://www.sqlteam.com/article/intro-to-user-defined-functions-updated
thanks
SenthilkumarPosted Apr 29, 2012, 10:28 PM
Lajapathy ArunPosted Apr 29, 2012, 11:47 AM
CREATE FUNCTION [dbo].[ufn_GenerateIntegers] ( @MaxValue INT )
RETURNS @Integers TABLE ( [IntValue] INT )
AS
BEGIN
DECLARE @Index INT
SET @Index = 1
WHILE @Index <= @MaxValue
BEGIN
INSERT INTO @Integers ( [IntValue] ) VALUES ( @Index )
SET @Index = @Index + 1
END
RETURN
END
GO