How can I convert format of a date string DDMMYYYY (ex: 31012010) to DD/MM/YY (ex: 31/01/2010) in SQL server 2008?
4 Answers
It's an old question, but I ended up here in Feb 2018, so...
In SQL Server 2012+ consider Format
- ref https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql (B and D)
For 2008 and above:
declare @d char(8)
-- string manipulation assumes clean data
set @d = '31012010'
SELECT LEFT(@d, 2) +'/'+ SUBSTRING(@d, 3, 2) +'/'+ RIGHT(@d, 4) As [with slashes]
String manipulation can be inefficient - make sure you understand the impact.
E.g. you would never put this code in a join clause (may be okay on a reporting server).
Personal opinion: the answer from Mark Byers STUFF(STUFF(@d, 3, 0, '/'), 6, 0, '/')) certainly works, but I think it is less maintainable if you have non-DBAs working in your code. (STUFF ref https://learn.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql)