conversion of a varchar to a smalldatetime results in an out-of-range value

末鹿安然 提交于 2019-12-10 18:36:38

问题


The code:

strSql = "insert into table2 (transactiondate) values ('" & transactiondate & "')"

seems to be giving me the runtime error:

The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value

In the code, strSql is a String object and transactiondate is a Date object. In the SQL database however, transactiondate is a smalldatetime object.

I've tried changing the smalldatetime to a datetime (in the database) and I've tried transactiondate.toString() but with no success.

How can this be fixed?

Note: I know about the dangers of inline SQL. I am looking for a quick fix solution here and not a discussion about SQL injection.


回答1:


Try adding single quotes to your insert statement.

strSql = "insert into table2 (transactiondate) values ('" & transactiondate & "')"



回答2:


Two possible answers:

  1. You need to encapsulate your string in an apostrophe:

strSql = "insert into table2 (transactiondate) values ('" & transactiondate & "')"

  1. You're using a date before 1/1/1900 or after 6/6/2079 (the limits of smalldatetime)



回答3:


Use transactiondate.ToString("yyyy/MM/dd HH:mm:ss") or your prefered date format. If it remains, change 'sa' user default language, or whatever user you use, to your prefered language.




回答4:


Smalldatetime can only accept values for years > 1900 and < 2079 as well. I had a similar error to the one you posted where the solution was to filter out invalid years like such

where year(datecolumn) < 2079


来源:https://stackoverflow.com/questions/1111646/conversion-of-a-varchar-to-a-smalldatetime-results-in-an-out-of-range-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!