I have table in which there is a column named period_start
which is type of nvarchar.
And it has different types of date formats.
Ex.
1. 01122018 --ddmmyyyy
2. 01132018 --mmddyyyy
3. 20181802 --yyyyddmm
4. 20180214 --yyyymmdd
5. 2018-01-02--yyyy-mm-dd
6. 01/02/2018 --dd-mm-yyyy
7. 010218 --ddmmyy
These are the dates which i want to convert in database date format.
I tried writing this code but wasn't successful.
Create Function dbo.[ConvStrToDate]
(@str nvarchar(50))
Returns Date
As
Begin
Declare @ConvertedDate Date;
Set @str = convert(date,@str,104)
Return @ConvertedDate
End
Real Data Example..
This works for all the examples you've given us, and I've had to utterly guess your design, as you haven't posted that DDL and DML I requested. The CONVERT (Transact-SQL) documentation is your friend here, so if you have more styles you haven't supplied, I suggest using that page as a guide to get the results you need.
CREATE TABLE dbo.StringDates (NotDate varchar(12),
FormatString varchar(12));
GO
INSERT INTO dbo.StringDates (NotDate,
FormatString)
VALUES('01122018','ddmmyyyy'),
('01132018','mmddyyyy'),
('20181802','yyyyddmm'),
('20180214','yyyymmdd'),
('2018-01-02','yyyy-mm-dd'),
('01/02/2018','dd-mm-yyyy'),
('010218','ddmmyy');
GO
SELECT CASE FormatString WHEN 'ddmmyyyy' THEN TRY_CONVERT(date, STUFF(STUFF(NotDate,5,0,'/'),3,0,'/'),103)
WHEN 'mmddyyyy' THEN TRY_CONVERT(date, STUFF(STUFF(NotDate,5,0,'/'),3,0,'/'),101)
WHEN 'yyyyddmm' THEN TRY_CONVERT(date,CONCAT(LEFT(NotDate,4), RIGHT(NotDate,2),SUBSTRING(NotDate, 5,2)),112)
WHEN 'yyyymmdd' THEN TRY_CONVERT(date,NotDate,120)
WHEN 'yyyy-mm-dd' THEN TRY_CONVERT(date,NotDate,121)
WHEN 'dd-mm-yyyy' THEN TRY_CONVERT(date,REPLACE(NotDate,'-','/'),103)
WHEN 'ddmmyy' THEN TRY_CONVERT(date, STUFF(STUFF(NotDate,5,0,'/'),3,0,'/'),3)
END,
FormatString
FROM dbo.StringDates
There is, however, only one real solution here. Fix that data type:
UPDATE StringDates
SET NotDate = CONVERT(varchar(8),CASE FormatString WHEN 'ddmmyyyy' THEN TRY_CONVERT(date, STUFF(STUFF(NotDate,5,0,'/'),3,0,'/'),103)
WHEN 'mmddyyyy' THEN TRY_CONVERT(date, STUFF(STUFF(NotDate,5,0,'/'),3,0,'/'),101)
WHEN 'yyyyddmm' THEN TRY_CONVERT(date,CONCAT(LEFT(NotDate,4), RIGHT(NotDate,2),SUBSTRING(NotDate, 5,2)),112)
WHEN 'yyyymmdd' THEN TRY_CONVERT(date,NotDate,120)
WHEN 'yyyy-mm-dd' THEN TRY_CONVERT(date,NotDate,121)
WHEN 'dd-mm-yyyy' THEN TRY_CONVERT(date,REPLACE(NotDate,'-','/'),103)
WHEN 'ddmmyy' THEN TRY_CONVERT(date, STUFF(STUFF(NotDate,5,0,'/'),3,0,'/'),3)
END,112);
ALTER TABLE dbo.StringDates ALTER COLUMN NotDate date;
SELECT *
FROM dbo.StringDates;
GO
--clean up
DROP TABLE dbo.StringDates;