About Me

My photo
Jody Morgan is a Systems and Software Architect. Since 1999, Jody has developed a distinctive approach to solving business needs with Microsoft Technologies. Jody has worked in the Manufacturing, Retail, Transportation/Logistics, Healthcare, Staffing firms as well as for the Federal Government. Jody is strong in the Windows Application and back office architecture. He has help write coding standards along with patterns and practices for specific clients to fit their needs and unique conditions. Proficient in C# and VB as well as SQL Script. Jody has worked hard to collect a broad knowledge base of both software development and IT infrastructure to blend with his ability to help understand and solve business needs of his clients. Jody is passionate about sharing knowledge and educating the masses. “Knowledge leads to meditation which leads to insight which leads to inspiration. Without Inspiration we would all still live in caves and carry clubs.” -Jody

Thursday, June 23, 2011

Create A SQL Function for Month

Yes I know that there is a function already that return the “Month” as an Integer. But what about the month as text. Take for example the month is 6 and you want June.

Well the following Function will allow this to happen.

Pretty simple to use. Just pass in a datatime and it returns a varchar(12) of the month.

Sample how to use:

SELECT dbo.MonthString(GetDate()) AS [Month]

Function Create Script:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[MonthString]
(
@Date DATETIME
)
Returns VARCHAR(12)
Begin

DECLARE @Month VARCHAR(12)

SELECT @Month = ( SELECT
CASE MONTH(@Date)
WHEN 1 THEN 'Januraury'
WHEN 2 THEN 'Feburaury'
WHEN 3 THEN 'March'
WHEN 4 THEN 'April'
WHEN 5 THEN 'May'
WHEN 6 THEN 'June'
WHEN 7 THEN 'July'
WHEN 8 THEN 'August'
WHEN 9 THEN 'September'
WHEN 10 THEN 'October'
WHEN 11 THEN 'November'
ELSE 'December'
END

)
RETURN @Month
End

No comments:

Post a Comment