简体   繁体   中英

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. 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 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() .)

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