我正在尝试运行以下代码,但错误发生在您说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;
}
答案 0 :(得分:3)
我有两种方法可以解决这个问题:
将SQL的相关部分更改为:
and (T_Id = @tid or @tid is null)
这将导致两个不同的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);
答案 1 :(得分:1)
问题可能出在if
声明中:
if (TId != null)
在c#中,long
变量永远不会为空,除非您将其声明为long?
,因此请检查调试器的值是否正确。如果此处TId
不为空,则您的函数不会将DBNull.Value
发送到数据库。
答案 2 :(得分:0)
试
T_Id = @tid
因为你正在发送dbnull.value。 否则调试并检查参数值。