You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行带日期参数的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 06:59:33