简体   繁体   English

空值检查

[英]NULL value checking

I am trying to run the following code but the error occurin says you have error near the @tid. 我正在尝试运行以下代码,但是发生的错误表示您error near the @tid.error near the @tid. The parameter is supposed to be taking NULL value. 该参数应采用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;
}

There are two ways I would handle this: 我有两种处理方式:

  1. Rewrite the SQL 重写SQL
  2. Rewrite the entire code 重写整个代码

1. Rewrite the SQL 1.重写SQL

Change the relevant portion of your SQL to this: 将SQL的相关部分更改为此:

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

2. Rewrite the entire code 2.重写整个代码

This will result in two different SQL statements depending on the parameter (to the code) value: 这将导致两个不同的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);

The problem might be in the if statement: 问题可能出在if语句中:

if (TId != null)

In c# a long variable is never null, unless you declare it as long? 在C#中, long变量永远不会为null,除非您将其声明为long? so please check with the debugger if its value is correct. 因此,请与调试器检查其值是否正确。 If TId is not null here, your function will not send DBNull.Value to the database. 如果TId不为null,则您的函数不会将DBNull.Value发送到数据库。

try 尝试

T_Id = @tid T_Id = @tid

because you are sending the dbnull.value right. 因为您正在发送dbnull.value权限。 else debug and check the values of parameters. 否则调试并检查参数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM