简体   繁体   English

SQL Server - 在ALTER TABLE中将VarChar转换为Date

[英]SQL Server - Convert VarChar to Date in ALTER TABLE

Saw a few threads on this but I have a specific instance where I am trying to do the conversion within an ALTER TABLE statement. 看到一些线程,但我有一个特定的实例,我试图在ALTER TABLE语句中进行转换。

ALTER TABLE Leads
ALTER COLUMN [Created Date] Date

This is throwing an error: 这是一个错误:

Msg 241, Level 16, State 1, Line 34 Msg 241,Level 16,State 1,Line 34
Conversion failed when converting date and/or time from character string. 从字符串转换日期和/或时间时转换失败。
The statement has been terminated. 该语句已终止。

Created Date is currently set as (varchar(max), null) 创建日期当前设置为(varchar(max),null)

You could standardize the date format. 您可以标准化日期格式。 Something like this: 像这样的东西:

UPDATE Leads
    SET [Created Date] = TRY_CONVERT(Date, [Created Date], 101);

The third argument is for the MM/DD/YYYY format mentioned in a comment. 第三个参数是注释中提到的MM / DD / YYYY格式。 This will convert the value to a date -- if it can -- and to NULL otherwise. 这会将值转换为日期(如果可以),否则转换为NULL Then, SQL Server will use its default formats to convert back to a string. 然后,SQL Server将使用其默认格式转换回字符串。

NOTE: If you do this, be sure you back up the table, so you don't lost the information in the column! 注意:如果这样做,请确保备份表,以免丢失列中的信息!

Then, your code should work: 然后,您的代码应该工作:

ALTER TABLE Leads ALTER COLUMN [Created Date] Date;

You can find the rogue values by using: 您可以使用以下方法找到恶意值:

select [Created Date]
from Leads
where try_convert(date, [Created Date], 101) is null and
      [Created Date] is not null;

As per Jarlh: 按照Jarlh的说法:

ALTER TABLE Leads
ADD COLUMN CreatedDate Date;

UPDATE Leads
SET CreatedDate = cast(right([Created Date],4) + '-' + left([Created Date],2) + '-' + left(right([Created Date],7),2) as Date);

Alter TABLE Leads
DROP COLUMN [Created Date];

sp_rename 'Leads.CreatedDate', '[Created Date]', 'COLUMN';

我认为你必须创建临时表,然后将所有记录插入临时表,然后重命名临时表和原始表

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

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