You're a good looking blog, what's your owner's name?

Richard Jonas's blog about .NET, web development and agile methodologies.

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

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home