I am trying to run the following code but the error occurin says you have error near the @tid.
The parameter is supposed to be taking NULL value.
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:
Change the relevant portion of your SQL to this:
and (T_Id = @tid or @tid is null)
This will result in two different SQL statements depending on the parameter (to the code) value:
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 (TId != null)
In c# a long
variable is never null, unless you declare it as 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.
try
T_Id = @tid
because you are sending the dbnull.value right. else debug and check the values of parameters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.