[英]NULL value checking
我正在尝试运行以下代码,但是发生的错误表示您error near the @tid.
有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;
}
我有两种处理方式:
将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);
问题可能出在if
语句中:
if (TId != null)
在C#中, long
变量永远不会为null,除非您将其声明为long?
因此,请与调试器检查其值是否正确。 如果TId
不为null,则您的函数不会将DBNull.Value
发送到数据库。
尝试
T_Id = @tid
因为您正在发送dbnull.value权限。 否则调试并检查参数值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.