c#字符串查询将SQL服务器参数设置为空

本文关键字:参数 设置 服务器 SQL 字符串 查询 | 更新日期: 2023-09-27 18:04:12

我知道这个问题已经被问过很多次了,但是我无法找到一个解决方案。

这是我的代码

  string query = @"SELECT *
    FROM SMSMessage
    WHERE (respondCode  IS @respondCode)
and (sentOn > '08/26/2016')
       ";
                //string query = "select * from SMSMessage";
                SqlConnection con = new SqlConnection(Utilities.getConnectionString());
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@respondCode", DBNull.Value);

我希望responseCode为null,

我得到错误:

@responseCode语法错误

当我做这个responseCode is NULL时,没有语法错误,但由于某种原因,查询没有带来任何结果

帮助请

c#字符串查询将SQL服务器参数设置为空

我会直接使用IS NULL,不传递任何参数,但最重要的变化是如何在查询语句中应用日期常数。
假设您在sql server数据库中使用意大利语区域设置,我将使用

string query = @"SELECT * SMSMessage
                 WHERE respondCode  IS NULL
                 AND (sentOn > CONVERT(DateTime, '26/08/2016', 105))

T-SQL转换文档

相反,我会仔细查看传递给sentOn条件的值。如果这个值是动态变化的,那么最好使用参数来表示这个值。这样,sql server的查询优化器将能够建立一个更好(更快)的执行计划

string query = @"SELECT * SMSMessage
                 WHERE respondCode  IS NULL
                 AND sentOn > @dateLimit";
SqlConnection con = new SqlConnection(Utilities.getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("@dateLimit", SqlDbType.DateTime).Value = new DateTime(2016, 8, 26);

我猜你想要这个

Where (respondCode = @respondCode or @respondCode is null)
  and sentOn > '08/26/2016'

当一个值传递给@respondCode参数时,记录将根据@respondCodesentOn > '08/26/2016'进行过滤。

如果没有传递给@respondCode参数(即NULL),则记录将仅基于sentOn > '08/26/2016'进行过滤

正如Steve在评论中提到的,如果你只需要respondCodeNULL时的记录,那么不需要该变量,只需在Where子句中硬编码NULL条件

Where respondCode is null
  and sentOn > '08/26/2016'