简体   繁体   English

SQL Server:将列数据类型从datetime2更改为nvarchar,同时转换现有数据

[英]SQL Server: change column datatype from datetime2 to nvarchar, convert existing data simultaneously

Management would like to change a column in our database from datetime2 to nvarchar , basically storing a string of the date rather than a date&time value. 管理层希望将我们数据库中的列从datetime2更改为nvarchar ,基本上是存储日期字符串而不是date&time值。 What is the best way to do this? 做这个的最好方式是什么? The column already has data in it, so I need to change the data type as well as convert the existing values to text. 该列中已经有数据,因此我需要更改数据类型以及将现有值转换为文本。

(I've already tried to push back on this, but they have their reasons that aren't super relevant here) (我已经尝试过对此进行回退,但是它们的原因在这里并不重要)

Management is wrong. 管理是错误的。 Date/time values should be stored using proper data types. 日期/时间值应使用适当的数据类型存储。 In general, storing them as strings is not a best-practice. 通常,将它们存储为字符串不是最佳实践。

However, you can easily do this. 但是,您可以轻松地做到这一点。 In fact, you can simply do: 实际上,您可以简单地执行以下操作:

alter table t alter datecol nvarchar(255);

If you want the data in a particular format, then use update afterwards: 如果您想要特定格式的数据,请随后使用update

update t
    set datecol = convert(nvarchar(255), convert(datetime2, datecol), ?);

Note: if you just want a way to get a "pretty" date out of the table, use a computed column: 注意:如果只想从表中获取“漂亮”日期,请使用计算列:

alter table t add datecol_pretty as (convert(nvarchar(255), datecol, ?);

Where ? ? is the conversion format you want. 是您想要的转换格式。 (Or use format() .) (或使用format() 。)

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

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