Convert a simple text field date to a date in sql

I need to convert this type of nvarchar field to a date. The data in the field called F2 looks like this. 09222018. i want to convert to a date and have it look like 09/22/2018.

I’ve tried this, and get incorrect syntax.

select f2,
       cast(f2,as datetime)
FROM Testbk

tried this

select f2,
       convert(nvarchar,f2,101)
FROM Testbk

no previal…

>Solution :

Not completely sure, what you want to achieve: convert value to a date or dislay it in another format.
Please see below

declare @InF2 varchar(8)='09222018';
select @InF2,LEFT(@iNf2,2)+'/'+SUBSTRING(@InF2,3,2)+'/'+SUBSTRING(@InF2,5,4)AS VARCHAR_USA_DATE,
CONVERT(DATE,LEFT(@iNf2,2)+'/'+SUBSTRING(@InF2,3,2)+'/'+SUBSTRING(@InF2,5,4),101)AS DATE_converted

Leave a Reply