如何在SQL表中转换日期时间格式但保持日期不变?

huangapple go评论75阅读模式
英文:

How to convert datetime format but keep the dates the same in the table in SQL?

问题

我知道我可以使用CONVERT(varchar, GETDATE(), 20)来将当前日期格式化为yyyy-MM-dd HH:mm:ss的格式,但是否有一种方法可以将日期转换为这种格式,同时保持日期的值不变?

英文:

Suppose I have the following table in myTable:

Name    |Date
------------------------------
A       | 12-23-2019 00:00:00
B       | 12-24-2019 00:00:00
C       | 12-25-2019 00:00:00

Where the datetime is formatted as MM-DD-yyyy HH:mm:ss.

I know I can use CONVERT(varchar, GETDATE(), 20) to convert the format using the current date. Is there a way to do this where I convert the date to yyyy-MM-dd HH:mm:ss while keeping the values of the dates the same?

答案1

得分: 1

如果您的数据存储方式如此,那么您应该修复数据。我建议:

update t 
set date = convert(date, [date], 20);

alter table t alter column [date] date;

这将把列更改为真正的日期类型。然后您就不必担心奇怪的日期格式。

英文:

If your data is stored like this, then you should fix the data. I would suggest:

update t 
    set date = convert(date, [date], 20);

alter table t alter column [date] date;

This will change the column to a bona fide date. Then you don't have to worry about arcane formats.

答案2

得分: 0

只需更新您的表格以符合新格式,或创建一个视图。

英文:

just update you table with your new format OR create a view

huangapple
  • 本文由 发表于 2020年1月7日 00:12:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定