Avoiding the TSQL ‘Convert’ styles.

Comments 0

Share to social media

A recent blog was extolling the advantages of being able to use the CLR routines in SQL Server 2005 to do Microsoft-style date formats, instead of having the fuss and bother of remembering the CAST or CONVERT styles for the various representations of dates

It is actually quite easy to do these date formats  in SQL 2000 as well, with a function. The advantage of using a function is that you can add your own favourite date formats in to taste. If your programmers are PHP programmers rather than ‘softies, you can even change it for the PHP date formatting convention.

Here is the straight-forward function
I was going to add a few esoteric bits and pieces such as the obvious one of being able to add the ‘st’, ‘nd’, ‘rd’, and ‘th’ suffix (as in ’21st March 2006′) bit the function was beginning to get a bit long for a blog. The reason the function was getting long was that I use the built-in date formats wherever possible before iterating through the format string only to do a ‘special’.

There is more optimisation to be had, possibly at the expense of the clarity of the code.I’d already written it when I realised that there should be just one loop, with the standards peeling off at the first iteration. It maybe should be done in a table rather than using all those case statements but I doubt that one gains a great deal in performance. I’d be interested to hear from anyone who spots a bug or can suggest an improvement. I’d love to do an extention that represented the time the way one speaks it in english, with ‘Ten to one’ or ‘quarter to four’, ‘half past six’ and so on, but that will have to wait for another occasion.

Load comments

About the author

Phil Factor

See Profile

Phil Factor (real name withheld to protect the guilty), aka Database Mole, has 40 years of experience with database-intensive applications. Despite having once been shouted at by a furious Bill Gates at an exhibition in the early 1980s, he has remained resolutely anonymous throughout his career. See also :

Phil Factor's contributions