What are Table Valued Functions in Sql ?
There are two types of “User Defined” fucntions in sql server
3. return (select * from table_name).
1. Inline Table Valued Functions
If function is made to execute a select query with or without parameters and return result as table type it comes in category of Inline table valued functions.
CREATE FUNCTION GetAuthorsByState( @state char(2) )
RETURNS table AS
RETURN (SELECT au_fname, au_lname FROM Authors WHERE state=@state)
GO
2. Multi-statement table valued Functions
Multi-statement table valued that returns function result in tabulated form but query may have multiple statements that can make changes to query and return the tabulated data.
If functions is made to execute multiple sql statements including insert, update statements etc and return result as table type then it comes in category of Multistatement table valued functions
Example
RETURNS
@AuthorsByState table (
au_id Varchar(11),
au_fname Varchar(20)
)
AS
BEGIN
INSERT INTO @AuthorsByState
SELECT au_id,au_fname FROM Authors WHERE state = @state
IF @@ROWCOUNT = 0
BEGIN
INSERT INTO @AuthorsByState VALUES ('','No Authors Found')
END
RETURN
END
GO
- scalar function ( that returns single value in response to function call )
3. return (select * from table_name).
1. Inline Table Valued Functions
If function is made to execute a select query with or without parameters and return result as table type it comes in category of Inline table valued functions.
CREATE FUNCTION GetAuthorsByState( @state char(2) )
RETURNS table AS
RETURN (SELECT au_fname, au_lname FROM Authors WHERE state=@state)
GO
2. Multi-statement table valued Functions
Multi-statement table valued that returns function result in tabulated form but query may have multiple statements that can make changes to query and return the tabulated data.
If functions is made to execute multiple sql statements including insert, update statements etc and return result as table type then it comes in category of Multistatement table valued functions
Example
RETURNS
@AuthorsByState table (
au_id Varchar(11),
au_fname Varchar(20)
)
AS
BEGIN
INSERT INTO @AuthorsByState
SELECT au_id,au_fname FROM Authors WHERE state = @state
IF @@ROWCOUNT = 0
BEGIN
INSERT INTO @AuthorsByState VALUES ('','No Authors Found')
END
RETURN
END
GO