如何在T-SQL中将varchar转换为datetime?

GLP*_*GLP 8 datetime varchar sql-server-2008

我试图从填充数据table1table2,两者具有相同的列数.

所有列table1都是类型varchar.列table2可以是varchar,intdatetime等.

我的问题是如何在填充期间进行转换?

这是我写的一个示例查询.我想念转换的部分.我的格式datetime也是mm/dd/yyyy hh:mm:ss.

insert into table2
    select s.acty_id, s.notes_datetime, s.notes_data
    from table1 t right join table2 s 
    on (t.acty_id =s.acty_id and t.notes_datetime =s.notes_datetime)
    where t.acty_id is null
Run Code Online (Sandbox Code Playgroud)

Tar*_*ryn 12

您将在您的领域使用CAST()CONVERT():

Declare @dt varchar(20)
set @dt = '08-12-2012 10:15:10'
select convert(datetime, @dt, 101)
Run Code Online (Sandbox Code Playgroud)

对于您的查询,您将执行以下操作:

insert into table2
select s.acty_id, s.notes_datetime, s.notes_data
from table1 t 
right join table2 s 
    on t.acty_id =s.acty_id 
    and convert(datetime, t.notes_datetime, 101) = s.notes_datetime
where t.acty_id is null
Run Code Online (Sandbox Code Playgroud)


Aar*_*and 5

正确的答案是纠正table1,以便它使用正确的数据类型.在此期间,假设您需要匹配日期和时间,您可以尝试这样做:

and CONVERT(DATETIME, t.notes_datetime, 101) = s.notes_datetime
Run Code Online (Sandbox Code Playgroud)