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

在C#中调用SQL标量函数fn_get_date传递日期参数报错

问题原因及解决方法

你的问题出在直接将DateTime变量拼接进SQL字符串,这种方式会因为日期格式的本地化差异(比如系统默认日期格式是MM/DD/YYYY还是DD/MM/YYYY)导致SQL服务器无法正确解析日期值,同时还存在SQL注入的安全风险。

正确的做法是使用参数化查询,通过SqlParameter传递参数,让ADO.NET自动处理日期类型的转换,避免格式问题和注入风险。修改后的代码如下:

public DateTime? get_settlement_date(DateTime startDate, int numberOfDays, string calendar)
{
    using (var connection = new SqlConnection(_connection_string))
    {
        connection.Open();

        // 使用参数占位符代替直接拼接变量
        var query = "SELECT [Dbo].[fn_get_date] (@StartDate, 1, 1, 1, 1)";

        var objCommand = new SqlCommand(query, connection);
        // 添加参数并指定类型,确保SQL能正确识别
        objCommand.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = startDate;

        var settlement_Date = objCommand.ExecuteScalar();

        return settlement_Date != DBNull.Value ? (DateTime)settlement_Date : null;
    }
}

额外说明

  • 参数化查询不仅解决了日期格式的问题,还能有效防止SQL注入攻击,这是数据库操作的最佳实践。
  • 注意判断ExecuteScalar()的返回值是否为DBNull.Value,避免强制转换时出现空引用异常。

内容的提问来源于stack exchange,提问作者Chatra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:07:05