Click here to Skip to main content
16,004,479 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,


when I am inserting values into a database table, I am getting exception for datetime varaibles:

Here is my query>

INSERT INTO [dbo].[DOMAIN] ([CREATED_DATE], [LAST_UPDT_DATE]) VALUES (cast('16/02/2016 12:58:45 a.m.' as DATETIME),cast('16/02/2016 12:58:45 a.m.'as DATETIME));

Error Msg:
Conversion failed when converting date and/or time from character string.

note:I set my system region settings to non US, so date foramt will be like:16/02/2016 12:58:45 a.m.

What I have tried:

INSERT INTO [dbo].[DOMAIN] ([CREATED_DATE], [LAST_UPDT_DATE]) VALUES (cast('16/02/2016 12:58:45 a.m.' as DATETIME),cast('16/02/2016 12:58:45 a.m.'as DATETIME));
Posted

1 solution

Probably, it's the "a.m." part of your date / time value.
I'm pretty sure you aren't entering that query manually, but from an application - so change the application to pass the DateTime value directly. If you don't, then when you change "a.m." to "am" or "AM" then you are likely to meet your next problem:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Because SQL assumes US format dates rather than European, and treats "16" as the month number.
Always pass validated data in storable form to SQL - numbers as integer or float values, dates as DateTime values - as parameters instead of concatenating strings: it's a lot safer, and it reduces the chance of errors in conversion.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900