How to convert varchar to datetime in T-SQL?

元气小坏坏 提交于 2020-07-18 10:25:19

问题


I am trying to populate the data from table1 to table2, both have the same number of columns.

All the columns in table1 are of type varchar. The columns in table2 could be varchar, int or datetime, etc.

My question is how to do the conversion during the populating?

This is a sample query that I wrote. I miss the part to do the conversion. Also the format of my datetime is 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

回答1:


You will use a CAST() or CONVERT() on your field:

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

For your query you would do the following:

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



回答2:


The right answer is to correct table1 so that it is using the right data types. In the meantime, assuming you need to match both date and time, you can try this:

and CONVERT(DATETIME, t.notes_datetime, 101) = s.notes_datetime


来源:https://stackoverflow.com/questions/12099059/how-to-convert-varchar-to-datetime-in-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!