2

我正在尝试运行以下代码,但发生的错误说您有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;
}
4

3 回答 3

3

我有两种处理方法:

  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);
于 2013-05-19T11:39:59.227 回答
1

问题可能出在if语句中:

if (TId != null)

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

于 2013-05-19T11:37:44.497 回答
0

尝试

T_Id = @tid

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

于 2013-05-19T11:28:55.000 回答