[英]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.