Technical Article

Date Format

,

Many clients require data to be sent to them in various formats.  Some require fixed length while others require delimited files.  Whatever the case may be the contents of the file also vary. Some may want you to send date information in mm/dd/yy and others yet want to see it as mmddy.  SQL Server has many built in conversion that will accomplish this, but as i came to find out with my most recent client request, some are just not available.  This being the case i came up with this function which will allow you to pass what format you need your date to be and have it converted for you.  My situation was the client wanted to have the date as mmddyy so after creating the function i tested it and eureka!!  Call the function as follows:  Select dbo.fnDateFormat(getdate(),'mmddyy')  The function also allows for special characters such as / and -.

select dbo.fnDateFormat(GETDATE(),'mm/dd/yyyy')

This function allows for a much cleaner code since i am using bcp to generate the fixed length file i wanted to save time and space in my code by not having to write all the code out in a statement, which as we all know, can get very lenghty and confusing.  

Hope this is benefical to all.  Enjoy!!

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fnDateFormat] (@Datetime DATETIME, @Format VARCHAR(32))
RETURNS VARCHAR(32)
AS
BEGIN
    DECLARE @DateValue VARCHAR(32)
    
    SET @DateValue = @Format
    
    IF (CHARINDEX ('YYYY',@DateValue) > 0)
       SET @DateValue = REPLACE(@DateValue, 'YYYY',
                         DATENAME(YY, @Datetime))
    IF (CHARINDEX ('YY',@DateValue) > 0)
       SET @DateValue = REPLACE(@DateValue, 'YY',
                         RIGHT(DATENAME(YY, @Datetime),2))
    IF (CHARINDEX ('Month',@DateValue) > 0)
       SET @DateValue = REPLACE(@DateValue, 'Month',
                         DATENAME(MM, @Datetime))
    IF (CHARINDEX ('MON',@DateValue)>0)
       SET @DateValue = REPLACE(@DateValue, 'MON',
                         LEFT(UPPER(DATENAME(MM, @Datetime)),3))
    IF (CHARINDEX ('Mon',@DateValue) > 0)
       SET @DateValue = REPLACE(@DateValue, 'Mon',
                          LEFT(DATENAME(MM, @Datetime),3))
    IF (CHARINDEX ('MM',@DateValue) > 0)
       SET @DateValue = REPLACE(@DateValue,'MM', 
  RIGHT('0'+CONVERT(VARCHAR,DATEPART(MM, @Datetime)),2))
    IF (CHARINDEX ('M',@DateValue) > 0)
       SET @DateValue = REPLACE(@DateValue,'M',
                         CONVERT(VARCHAR,DATEPART(MM, @Datetime)))
    IF (CHARINDEX ('DD',@DateValue) > 0)
       SET @DateValue = REPLACE(@DateValue, 'DD',
                         RIGHT(0+DATENAME(DD, @Datetime),2))
    IF (CHARINDEX ('D',@DateValue) > 0)
       SET @DateValue = REPLACE(@DateValue,'D',
                                     DATENAME(DD, @Datetime))   
RETURN @DateValue
END

Rate

4.4 (5)

Share

Share

Rate

4.4 (5)