P
P
Pavel2015-10-29 14:33:26
ASP.NET
Pavel, 2015-10-29 14:33:26

How to catch date cast error in C#?

There are 2 computers: dev and server.
On the developer's machine, the request is processed normally, but an exception is thrown on the server:

System.Data.SqlClient.SqlException: Converting a varchar data type to a datetime data type resulted in an out of range value.

Here is the request:
SELECT COUNT(*) FROM view_Request 
WHERE ( ( Executor.exist('(/Items/Item[@id="paco"])[1]') = 1) 
AND  ( StatusName = 'в работе' OR StatusName = 'не рассмотрена' OR StatusName = 'обязательно сегодня') 
AND  ( Created >= '2015-10-19' AND Created <= '2015-10-26'))

Interestingly, if I execute this query in MS SQL Management Studio, everything works fine both on dev and on the server. But in the code on the 3rd line an exception flies:
var da = new SqlDataAdapter(sqlQuery, con);
var dt = new DataTable();
da.Fill(dt);

Where to look, what to edit? I looked at the IIS configuration - the locale is the same. In the SQL server, too, the settings are identical. What did I miss?

Answer the question

In order to leave comments, you need to log in

6 answer(s)
Z
Zelimkhan Beltoev, 2015-10-29
@region23

Have you tried writing the date in standard format? How would always get rid of problems of this kind
For those who are in a similar situation, but did not get to the comments:

TRY_PARSE('26/10/2015 00:00:00' AS DATETIME USING 'ru-ru')

G
GavriKos, 2015-10-29
@GavriKos

The date format depends on the regional settings of the particular machine.

M
mletov, 2015-10-29
@mletov

And also look in Web.Config, add a line something like this (choose the culture value yourself), I had this when I had Russian Windows on the LAN, English on the server. Moreover, changing the language settings of the machine itself did not help, but changing the Web.config worked.
<globalization uiCulture="ru" culture="ru-RU" />

H
heartdevil, 2015-10-29
@heartdevil

Hello.
I think this can happen if the date format is incorrect.

E
eRKa, 2015-10-29
@kttotto

It's all about the date format. When writing it, you need to take into account the culture where you will read it.

A
Anton Papin, 2015-11-05
@i_light

Well, apart from the fact that you are using plain sql in the code in the 21st century, instead of using one of the wonderful ORMs,
you forgot that in such operations it is useful to insert SET DATEFORMAT
at the beginning of the script. However, I still strongly recommend using the ORM. Entity Framework, NHibernate, or whatever you like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question