9

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

2 Answers 2

14

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
5
  • Sorry, didn't see your edit, but a couple of things: table1 is where the varchar exists, not table2, and you need to do a safe cast so you should use convert with a style that matches the string format (m/d/y) so that you don't end up with problems on a non-US English system or with different session settings. Commented Aug 23, 2012 at 20:06
  • @AaronBertrand I caught the varchar in table1 and edited it to correct that mistake. Too many table1, table2's. You are right about the correct, conversion format too...as always
    – Taryn
    Commented Aug 23, 2012 at 20:08
  • I am not sure I understand the first part. can you explain? will this work? insert into table2 select s.acty_id, convert(datetime, s.notes_datetime, s.notes_data, 101), 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
    – GLP
    Commented Aug 24, 2012 at 1:46
  • It seems work. But if I put 12/23/2012 12:00:01 (varchar), it will convert to 2012-12-31 12:00:01.000 (datetime). I used convert(datetime, colname, 101). what should I do to keep the value as 12/23/2012 12:00:01 as a datetime type?
    – GLP
    Commented Aug 24, 2012 at 3:41
  • @GaolaiPeng it is working for me, see this sql fiddle sqlfiddle.com/#!3/2fec5/1
    – Taryn
    Commented Aug 24, 2012 at 4:11
5

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.