简体   繁体   中英

SQL SERVER Convert Date Format

Now in the column store string in three different format. Example such

  • 2/04/15 9.30-12
  • 10/01/2015 10am - 1pm
  • 17/03/15 1st appt

How can I to convert the all the date to consolidate to stardard date like ddmmyyy? Use Left 10 is not appropriate.

Following is my solution for SQL2012:

DECLARE @Date AS TABLE(val VARCHAR(30));

INSERT INTO @Date VALUES('2/04/15 9.30-12');
INSERT INTO @Date VALUES('10/01/2015 10am - 1pm');
INSERT INTO @Date VALUES('17/03/15 1st appt');

SELECT TRY_PARSE(LEFT(val, CHARINDEX(' ', val)) AS DATE USING 'en-gb') AS Date FROM @Date;

And the output is:

在此处输入图片说明

Will try to find out something for 2008 too. possibly.

Use try_convert() . And then try_convert() again. Perhaps something like:

select coalesce(try_convert(date, left(col, charindex(' ', col + ' ') - 1), 1),
                try_convert(date, left(col, charindex(' ', col + ' ') - 1), 101),
                try_convert(date, left(col, charindex(' ', col + ' ') - 1), 103),
                . . .
               ) as dte
from t;

Just keep trying different styles. Be careful that these are ordered. So, you have to decide if 02/01/2012 is February 1st or January 2nd.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM