Scalar And Inline Table Functions In T-SQL and SQL Server
After reading some articles on TSQL, I made some experiments on User defined functions. Actually, there are three types of UDF. First we have the Scalar functions that returns a single value of the data type referenced in the RETURNS clause of the CREATE FUNCTION statement. The returned data can be of any type except text, ntext, image, cursor, or timestamp. Next we have Inline table-valued function which returns a variable of data type table whose value is derived from a single SELECT statement. Lastly, we have multi-statement table-valued function which is slightly more complicated than the other two types of functions because it uses multiple statements to build the table that is returned to the calling statement.
(Source: http://www.sqlteam.com)
For the sake of simplicity, I'll tackle the first two types of functions.
1. Scalar function example:
Note: As you can see, the function takes two arguments of type int. Then on the function body, the computation proceeds, then calls the return statement.
--to execute function
15 will be displayed as output
2. Inline Table Functions (make sure you have adventureworks db in your sql server)
The output returned is: 75123 which is the latest order generated.
(Source: http://www.sqlteam.com)
For the sake of simplicity, I'll tackle the first two types of functions.
1. Scalar function example:
create function ComputeSum(@FirstNum int, @SecondNum int) returns int as begin Declare @sum int set @sum = (@FirstNum + @SecondNum) return @sum end
--to execute function
declare @result int set @result = dbo.ComputeSum(5,10) print @result
2. Inline Table Functions (make sure you have adventureworks db in your sql server)
create function maxorder() returns table as return select max(SalesOrderID) as LastOrderID from Sales.SalesOrderHeader --execute the function select * from maxorder()
Comments
Post a Comment