Q:

how to convert Sql server Datetime in different format

I have a column that store date and time values in the format YYYY-MM-DD HH:MM:SS.MSS. I have another table that store date and time value as string in the format 'M/D/YYYY HH:MM:SS AM'. 
Now how do I convert  YYYY-MM-DD HH:MM:SS.MSS this format to M/D/YYYY HH:MM:SS AM. After conversion can I able to compare conversion date to the datetime string.
for e.g
A.Date_time = '2013-01-08 12:04:00.000'
B.Date_time = convert ( A.Date_time) -- convert in format M/D/YYYY HH:MM:SS AM
...
if(B.Date_time = 'convert (A.Date_time)' -- how can I can compare conversion date with the datetime string.
...

A:

Don't convert to string to compare, convert to dates to compare.
SELECT <cols>
  FROM A
  INNER JOIN B
  ON A.Date_time = CONVERT(DATETIME, B.Date_time, 101);

You may need to clean up data first - when you use a string to store a date (which you should never do for a variety of reasons), anyone can stuff any junk in there without validation. So there is no guarantee that all of your values can be successfully converted to a datetime. 
For the changed requirements we can try sussing the datetime portion of the terrible string in this way:
SELECT <cols>
  FROM A
  INNER JOIN B
  ON A.Date_time = CONVERT(DATETIME, 
   SUBSTRING(B.Date_time, CHARINDEX(' - ', B.Date_time) + 3, 255), 101);

You can even pull that out first, e.g.
;WITH x AS (SELECT B.Date_time, RealDateTime = CONVERT(DATETIME, 
   SUBSTRING(B.Date_time, CHARINDEX(' - ', B.Date_time) + 3, 255), 101)
   FROM B
)
SELECT x.Date_time, x.RealDateTime FROM x
-- add joins, comparisons, etc.

IMHO you should focus on fixing the data types, not working around the differences. Or at least arguing with the people who designed this mess to clean it up.

