执行带日期参数的SQL查询时遭遇日期转换失败错误的求助
执行带日期参数的SQL查询时遭遇日期转换失败错误的求助
嘿,我一眼就瞅出问题所在啦!你在SQL语句里把参数@startDateDate和@endDateDate用单引号括起来了,这可是参数化查询的大忌哦!
当你用参数化查询的时候,参数名周围绝对不能加单引号——加了之后,SQL会把'@startDateDate'当成一个普通的字符串常量,而不是你通过commandBlog.Parameters.AddWithValue传入的实际日期值。你想想,把字符串"@startDateDate"转换成日期,肯定会报错啊!
哪怕你后来加了convert(datetime, ...)也没用,因为你还是在尝试转换那个字符串字面量,根本没用到你传入的参数值。
来看看修正后的正确写法:
首先是SQL语句,去掉参数的单引号:
SELECT * FROM [dbo].[BlogSubcriptionSql] where Email like '%_@__%.__%' and Email not like '%|%' and CreationDate >= @startDateDate and CreationDate <= @endDateDate order by LastUpdate desc
然后你的C#参数部分是没问题的,保持原样就行:
commandBlog.Parameters.AddWithValue("@startDateDate", startDateDate); commandBlog.Parameters.AddWithValue("@endDateDate", endDateDate);
这样一来,数据库会自动识别@startDateDate是参数,然后把你传入的DateTime类型值正确匹配到CreationDate字段上,既不会有转换错误,还能避免SQL注入风险,一举两得!
备注:内容来源于stack exchange,提问作者SeeSharper
相关产品推荐
相关产品推荐

