Hey all I'm trying to do the following insert query
SqlDataSource userQuizDataSource = new SqlDataSource();
userQuizDataSource.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=quizApp;Integrated Security=True";
userQuizDataSource.InsertCommand = "INSERT INTO [UserQuiz] ([DateTimeComplete], [Score], [UserName]) VALUES (@DateTimeComplete, @Score, @UserName)";
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now.ToString());
userQuizDataSource.InsertParameters.Add("Score", score.ToString());
userQuizDataSource.InsertParameters.Add("UserName", User.Identity.Name);
int rowsAffected = userQuizDataSource.Insert();
Buti keep getting the following error:
The conversion of a nvarchar data type to a smalldatetime data type resulted in an out-of-range value. The statement has been terminated.
Can anyone help me out?
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. You need separators for the date like a “/”, a “.” or a “-“. We use substring to concatenate the “-” to use an acceptable date format and then we use the CONVERT function to convert the characters to sql date.
Answer: The error is due to an invalid date format being saved to the custom_rmh_rooms_history SQL table. To resolve this issue, the Windows Regional settings need to be modified and the Short Date format needs to be in MM/dd/yyyy format.
What does your statement DateTime.Now.ToString()
return??
What language and regional settings is your SQL Server expecting??
Do you have a mismatch there??? Maybe your .NET returns a MM/dd/yyyy
format, while SQL Server expects dd/MM/yyyy
(or vice-versa).
Try this code in your SQL Server:
DECLARE @test TABLE (smalldate SMALLDATETIME)
INSERT INTO @test VALUES ('02/21/2010 22:00:32') --
SELECT * FROM @test
Replace my string there with what output you got from .NET's DateTime.Now.ToString()
- does this work? Does SQL Server give you a better error message?
Next, try to use the ISO-8601 format for dates (YYYYMMDD) - this works for ALL regional and language settings in SQL Server - does this work??
DECLARE @test TABLE (smalldate SMALLDATETIME)
INSERT INTO @test VALUES ('20100221 22:00:32') --
SELECT * FROM @test
I had the same problem adding datetime.now into my SQL server column 'Date' set to datatype SmallDateTime.
To resolve it was quite simple (after many attempts!!)
string currentdatetime=
DateTime.Now.Year + "." + DateTime.Now.Month + "." + DateTime.Now.Day +
" " + DateTime.Now.Hour+(":")+DateTime.Now.Minute+(":")+DateTime.Now.Second
This will return the date into the format that the Server will expect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With