Friday, December 2

Swap day and month in SQL Server

I had an SQL Server database with days and months inserted the wrong way round, due to the code that was inserting them using European format (where the day is written before the month) and the database assuming it was in US format (month before the day).

If anyone's interested, here's a user defined function to swap the day and month around, leaving the year and time unchanged.


CREATE FUNCTION dbo.MonthDaySwap (@dt datetime)
RETURNS datetime AS
BEGIN
return convert(datetime,
convert(varchar(50),day(@dt))+'/'+
convert(varchar(50),month(@dt))+'/'+
convert(varchar(50),year(@dt))+' '+
CONVERT(varchar(12), @dt, 114)
)
END


You can use this in an update query as follows:


update dbo.Orders
set orderdate=dbo.MonthDaySwap(orderdate)
where orderid=5

5 comments:

Anonymous said...

Brilliant, many thanks

Anonymous said...

You saved my skin today, many thanks

Anonymous said...

Thanks for sharing this.

Best Dentist said...

I am glad to be a visitor of this perfect web blog! Regards for this rare information! The whole thing is going fine here and of-course every one is sharing data, that’s in fact fine, keep up writing.

Excellent Healthcare Website Design Company in America, Their designs are great and build specially for doctors like you.

Unknown said...

if order date is of character data type how do you work on it