【问题标题】:NULL value checkingNULL 值检查
【发布时间】:2013-05-19 11:22:17
【问题描述】:

我正在尝试运行以下代码,但发生的错误说您有 error near the @tid. 该参数应该采用 NULL 值。

 public static DataTable GetChapterArticlesSummary(long ChapterId, long? TopicId)
{
    DataTable TableArticles = new DataTable();
    try {
        using (SqlConnection connection = ConnectionManager.GetConnection())
        {
            SqlCommand command = new SqlCommand();
            command.CommandText = "Select Article_Name, Id, Privacy_Term from Articles where Chapter_Id=@chapterid and Topic_Id is @topicid";
            command.Parameters.Add("@chapterid", SqlDbType.BigInt).Value = ChapterId;
            if (TopicId != null)
            {
                command.Parameters.Add("@topicid", SqlDbType.BigInt).Value = TopicId;
            }
            else
            {
                command.Parameters.Add("@topicid", SqlDbType.BigInt).Value = DBNull.Value;
            }
            command.Connection = connection;
            SqlDataAdapter Adapter = new SqlDataAdapter();
            Adapter.SelectCommand = command;
            Adapter.Fill(TableArticles);
        }
    }
    catch (SqlException ex)
    { }
    return TableArticles;
}

【问题讨论】:

  • TId的类型和值是什么?
  • 我现在检查的值是 null..

标签: c# .net sql ado.net


【解决方案1】:

我有两种方法来处理这个问题:

  1. 重写 SQL
  2. 重写整个代码

1。重写SQL

将 SQL 的相关部分更改为:

and (T_Id = @tid or @tid is null)

2。重写整个代码

这将根据参数(对代码)的值产生两条不同的 SQL 语句:

SqlCommand command = new SqlCommand();
if (TId != null)
{
    command.CommandText = "Select Article_Name, Id, Privacy_Term from Articles where Id=@id and T_Id = @tid";
    command.Parameters.Add("@tid", SqlDbType.BigInt).Value = TId;
}
else
{
    command.CommandText = "Select Article_Name, Id, Privacy_Term from Articles where Id=@id and T_Id is null";
}
command.Parameters.Add("@id", SqlDbType.BigInt).Value = Id;
command.Connection = connection;
SqlDataAdapter Adapter = new SqlDataAdapter();
Adapter.SelectCommand = command;
Adapter.Fill(TableArticles);

【讨论】:

  • 好吧,这也是我的猜测。但是对于我检查的值,它是空的,所以我认为这是一个问题。
  • 抱歉,我再次使用了@topicid NULL
【解决方案2】:

问题可能出在if 语句中:

if (TId != null)

在 c# 中,long 变量永远不会为空,除非您将其声明为 long?,因此请检查调试器的值是否正确。如果此处TId 不为空,您的函数将不会将DBNull.Value 发送到数据库。

【讨论】:

  • @SpiralsWhirls,如果它在 if 中,您是否检查过调试器?
  • @SpiralsWhirls 您发布的新代码是错误的。您需要使用is 而不是=
【解决方案3】:

试试

T_Id = @tid

因为您发送的是正确的 dbnull.value。 否则调试并检查参数的值。

【讨论】:

  • 空检查的sql语法是is不是=
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 2021-02-19
  • 1970-01-01
  • 2011-02-24
  • 2016-01-10
  • 2012-01-02
  • 1970-01-01
相关资源
最近更新 更多