简体   繁体   中英

SQL Server Converting varchar to datetime

I got a problem in SQL Server with converting a varchar to datetime . I would like to convert/update whole column [datelog] in table:

[dd.mm.yyyy hh:mm:ss]` to `[yyyy-mm-dd hh:mm:ss]

Tricky solution,

DECLARE @inputDate AS VARCHAR(20)='21.11.2015 06:59:00' -- [dd.mm.yyyy hh:mm:ss]
SET @inputDate = REPLACE(@inputDate ,'.' ,'/')
SELECT CONVERT(VARCHAR(24) ,CONVERT(DATETIME ,@inputDate ,103) ,121) OutputDate -- [yyyy-mm-dd hh:mm:ss]

Still you need to change as per your table columns.

In SQL Server 2012+ you can use PARSE or TRY_PARSE to parse a text value according to a specific culture.

Assuming your text follows the German culture ('de-DE') you can parse it to datetime with :

select PARSE('24.11.2015 13:10:55' as datetime using 'de-DE')

eg:

select PARSE(datelog as datetime using 'de-DE')

The real solution though would be to use the correct field type, ie datetime . It's almost guaranteed that someone, somewhere will either enter text with the wrong format or try to convert the text using the wrong culture.

Date types on the other hand, have no format, they are simply binary values. Using them is faster, safer and easier.

temp table with one column of type varchar

create table #temp3 (someDate varchar (30))
insert into #temp3 values ('23.03.1989 15:23:43')

using a combination of concat, substring and right

select concat
(
SUBSTRING(someDate,7,4),'-', SUBSTRING(someDate,4,2),'-',SUBSTRING(someDate,1,2), ' ', right(someDate, 8)
)
from #temp3

gives: 1989-03-23 15:23:43

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