Creating a User-Defined Function : Create function « Procedure Function « SQL Server / T-SQL Tutorial






5> CREATE Function dbo.fn_LastOfMonth(@TheDate DateTime)
6> Returns DateTime
7> AS
8> BEGIN
9> DECLARE @FirstOfMonth  DateTime
10> DECLARE @DaysInMonth Int
11> DECLARE @RetDate DateTime
12> SET @FirstOfMonth = DATEADD(mm, DATEDIFF(mm,0,@TheDate), 0)
13> SET @DaysInMonth = DATEDIFF(d, @FirstOfMonth, DATEADD(m, 1, @FirstOfMonth))
14> RETURN  DATEADD(d, @DaysInMonth - 1, @FirstOfMonth)
15> END
16> GO
1>
2> drop function dbo.fn_LastOfMonth;
3> GO
1>








21.1.Create function
21.1.1.Scalar functions are functions that return a single value.
21.1.2.Syntax for Creating Inline Table-Valued Functions
21.1.3.Syntax for Creating Multistatement Table-Valued Functions
21.1.4.Creating a User-Defined Function
21.1.5.A statement that creates a simple table-valued function
21.1.6.A statement that creates a scalar-valued function