Sql query to insert datetime in SQL Server

Shee picture Shee · Oct 18, 2012 · Viewed 999.9k times · Source

I want to insert a datetime value into a table(SQL Server) using the sql query below

insert into table1(approvaldate)values(18-06-12 10:34:09 AM);

But I get this Error msg. Incorrect syntax near '10'.

I tried it with the quotes

insert into table1(approvaldate)values('18-06-12 10:34:09 AM');

I get this error message Cannot convert varchar to datetime

Kindly help! Thanks.

Answer

RichardTheKiwi picture RichardTheKiwi · Oct 18, 2012

You will want to use the YYYYMMDD for unambiguous date determination in SQL Server.

insert into table1(approvaldate)values('20120618 10:34:09 AM');

If you are married to the dd-mm-yy hh:mm:ss xm format, you will need to use CONVERT with the specific style.

insert into table1 (approvaldate)
       values (convert(datetime,'18-06-12 10:34:09 PM',5));

5 here is the style for Italian dates. Well, not just Italians, but that's the culture it's attributed to in Books Online.