NULL value checking

本文关键字:checking value NULL | 更新日期: 2023-09-27 18:14:14

我试图运行以下代码,但错误发生说你有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;
}

NULL value checking

我有两种处理方法:

    重写SQL重写整个代码

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);

问题可能在if语句中:

if (TId != null)

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

try

T_Id = @tid

,因为您正在发送dbnull。正确的价值。否则调试和检查参数值