简体   繁体   English

在 SQL Server 中将字符串日期转换为 GETDATE() 格式

[英]Convert string date to GETDATE() format in SQL server

We have a table employee with columns LastUpdated (datetime) , ExitDate (datetime) and ReleaseDate (varchar(50)) .我们有一个员工表,其中包含LastUpdated (datetime)ExitDate (datetime)ReleaseDate (varchar(50))

The date in the table is shown here:表中的日期如下所示:

+-------------------------+----------------------+
|       LastUpdated       |     ReleaseDate      |
+-------------------------+----------------------+
| 2019-05-24 01:19:21.597 | 4/8/2016 7:00:00 AM  |
| 2019-05-24 02:05:26.130 | 3/20/2007 7:00:00 AM |
| 2019-05-24 01:57:44.810 | 5/14/2007 7:00:00 AM |
| 2019-05-24 01:48:40.483 | 3/16/2010 7:00:00 AM |
| 2019-05-24 01:11:41.290 | 11/8/2018 8:00:00 AM |
+-------------------------+----------------------+

Now I want to convert the ReleaseDate column values into the LastUpdated column format ( yyyy-MM-dd HH:mm:ss ) and update the value to the column ExitDate .现在我想将ReleaseDate列值转换为LastUpdated列格式( yyyy-MM-dd HH:mm:ss )并将值更新为列ExitDate

The LastUpdated column value was inserted using GETDATE() in SQL Server. LastUpdated列值是在 SQL Server 中使用GETDATE()插入的。

Can anyone help with this, please?任何人都可以帮忙吗?

You can use update :您可以使用update

update employee
     set ExitDate = convert(datetime, ReleaseDate, 101);

However, storing date value into other format not a good practice.但是,将日期值存储为其他格式不是一个好习惯。

You can parse the string to a date, then convert the date to a string in the desired format.您可以将字符串解析为日期,然后将日期转换为所需格式的字符串。 The string formats supported for datetime conversions are documented here .日期时间转换支持的字符串格式记录在此处

So something like:所以像:

update employee set ReleaseDate = convert(varchar(50), convert(datetime,ReleaseDate, 101), 121);

if all the rows are in the same date format.如果所有行都采用相同的日期格式。 If the date format varies, you can try:如果日期格式不同,您可以尝试:

update employee set ReleaseDate = convert(varchar(50), convert(datetime,ReleaseDate), 121);

to convert using the your current culture settings and SQL Server's permissive conversion rules.使用您当前的区域性设置和 SQL Server 的许可转换规则进行转换。

But you should then alter the column's datatype, if, and when that is possible:但是您应该更改列的数据类型,如果可能,以及何时可能:

alter table employee alter column ReleaseDate datetime

or add a check constraint to force the application to make sure no other format is inserted.或者添加一个检查约束来强制应用程序确保没有插入其他格式。

alter table employee add constraint [ck_EnforceReleaseDateFormat_YYYY-MM-DD HH:MM:SS]
check (ReleaseDate = convert(varchar(50), convert(datetime,ReleaseDate, 121), 121))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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