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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Lajapathy ArunRank #354 · 7K reputationPosted Apr 29, 2012, 7:47 AM EDT
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
SenthilkumarRank #387 · 6.5K reputationPosted Apr 29, 2012, 6:28 PM EDT
MuthuMari MRank #5,738 · 288 reputationPosted Apr 29, 2012, 9:09 PM EDT
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 pls refer this url for more details http://www.sqlteam.com/article/intro-to-user-defined-functions-updated thanksLajapathy ArunRank #354 · 7K reputationPosted Apr 29, 2012, 11:45 PM EDT