I have tried with the following sample
SELECT
FORMAT(CONVERT(DATETIME,'01011900'), 'dd/MM/yyyy')
FROM
identities
WHERE
id_type = 'VID'
I have tried with the following sample
SELECT
FORMAT(CONVERT(DATETIME,'01011900'), 'dd/MM/yyyy')
FROM
identities
WHERE
id_type = 'VID'
Your data should be 19000101.So your input needs to be modified first then we need to use Convert to get your appropriate format.
declare @inp varchar(10) = '01011900'
select CONVERT(varchar, cast(right(@inp,4)+''+left(@inp,4) as datetime), 101)
--Output : 01/01/1900
Try this:
SELECT FORMAT(CONVERT(DATETIME,STUFF(STUFF('01011900',5,0,'/'),3,0,'/')),'dd/MM/yyyy')
Insert /
using STUFF
, and then convert it.
STUFF(STUFF('01011900',5,0,'/'),3,0,'/') -- 01/01/1900
Update:
I tried the following also,
DECLARE @DateString varchar(10) = '12202012' --19991231 --25122000
DECLARE @DateFormat varchar(10)
DECLARE @Date datetime
BEGIN TRY
SET @Date = CAST(@DateString AS DATETIME)
SET @DateFormat = 'Valid'
END TRY
BEGIN CATCH
BEGIN TRY
SET @DateFormat = 'ddMMyyyy'
SET @Date = CONVERT(DATETIME,STUFF(STUFF(@DateString,5,0,'/'),3,0,'/'))
END TRY
BEGIN CATCH
SET @DateFormat = 'MMddyyyy'
SET @Date = CONVERT(DATETIME,STUFF(STUFF(@DateString,1,2,''),3,0,
'/' + LEFT(@DateString,2) + '/'))
END CATCH
END CATCH
SELECT
@DateString InputDate,
@DateFormat InputDateFormat,
@Date OutputDate
Right now your question is absurd. There cannot be a generic format that can handle all the date formats, you need to provide that information to your query ( you would be much better of with a stored procedure in this scenario ) where you pass the date format string too. You could do something like this in your SELECT CASE
if the format is ddmmyyyy, do what JesuRaja suggested. But its already answered in SO
SELECT CONVERT (datetime, Stuff(Stuff('311012',5,0,'.'),3,0,'.'), 4)
if its mmddyyyy, see this answer
DECLARE @Date char(8)
SET @Date='12312009'
SELECT CONVERT(datetime,RIGHT(@Date,4)+LEFT(@Date,2)+SUBSTRING(@Date,3,2))
if its yyyymmdd, just do a CAST
SELECT CAST('20041223' AS datetime)
20122012
. Can you guess the date format?
Also, you cannot force the server to use /
as your separator. The SQL Server will use either /
, .
or -
depending on the Culture of the server.