問題背景:
在做考試系統(tǒng)手動生成試卷部分時由于題庫的表結(jié)構(gòu)不相同,導(dǎo)致同樣的Gridview(已模板化后的,其結(jié)構(gòu)已固定)在顯示時不能同時兩種不同結(jié)構(gòu)的數(shù)據(jù)。如GridView結(jié)構(gòu)如下所示:
這種固定的格式顯示的是以選擇題為代表的數(shù)據(jù)結(jié)構(gòu),但是因為選擇題題庫表結(jié)構(gòu)與論述題題庫表結(jié)構(gòu)不相同,所以無法直接顯示以論述題為代表的數(shù)據(jù)結(jié)構(gòu)。這時如何在這個固定的GridView中顯示不同的數(shù)據(jù)呢?其實在仔細(xì)觀察后我們可以發(fā)現(xiàn)他們唯一的區(qū)別在于“答案”這列的數(shù)據(jù)不同,在選擇題類型中,該字段的值僅為一個選項而已,但是對于論述題等類型,其問題有六個,對應(yīng)的答案也應(yīng)該有六列才對。分析到此,可以總結(jié)一下,最終要解決的問題是如何將六列的答案顯示在一列。
解決辦法:將六個字段中的內(nèi)容用sql語句實現(xiàn)合并,將其作為一個新的字段顯示出來,具體的實現(xiàn)請看代碼:
復(fù)制代碼 代碼如下:
#region 根據(jù)動態(tài)生成的數(shù)據(jù)庫表名,從該表中選出QuestionId,ChapterId,QuestionTypeId,Point,不包括難度等級約束
/// summary>
/// 根據(jù)動態(tài)生成的數(shù)據(jù)庫表名,從該表中選出QuestionId,ChapterId,QuestionTypeId,Point,
/// Degree,Fraction,QuestioinContent,IsValid等內(nèi)容,不包括難度等級約束
/// /summary>
/// param name="strDataTableName">/param>
/// returns>/returns>
public DataTable BindQuestion(string strTableName,string strChapterName,string strQuestionTypeName)
{
try
{
DataTable dt = new DataTable ();
if (strQuestionTypeName != "論述題" strQuestionTypeName != "案例分析題")
{
strsql = "select * from " + strTableName + " where ChapterId=@chapterid and QuestionTypeId=@questiontypeid";
}
else
{
strsql = "select QuestionId,ChapterId,QuestionTypeId,Point,Degree,Fraction,QuestionContent,cast(Answer1 as nvarchar(4000)) + cast(Answer2 as nvarchar(4000)) + cast(Answer3 as nvarchar(4000)) + cast(Answer4 as nvarchar(4000)) + cast(Answer5 as nvarchar(4000)) + cast(Answer6 as nvarchar(4000)) AS CorrectAnswer,IsValid from " + strTableName + " where ChapterId=@chapterid and QuestionTypeId=@questiontypeid";
}
//strsql = "select * from " + strTableName + " where ChapterId=@chapterid and QuestionTypeId=@questiontypeid";
SqlParameter[] paras = new SqlParameter[]{
new SqlParameter("@chapterid",strChapterName),
new SqlParameter("@questiontypeid",strQuestionTypeName)
};
dt = sqlHelper.ExecuteQuery(strsql,paras,CommandType.Text);
return dt;
}
catch
{
throw new Exception("從動態(tài)生成的數(shù)據(jù)庫表中獲取QuestionId,ChapterId,QuestionTypeId,Point失敗(不包括難度等級)");
}
finally
{
sqlHelper.Close();
}
}
#endregion
其中使用cast函數(shù)的strSql語句所起到的作用就是將多個字段合并成一個新字段。另外需要注意的是strSql語句中的 “ + ” 號,如果需要合并的字段的內(nèi)容是Text類型的,是不支持該符號的,這時我們需要將其轉(zhuǎn)換成nvarchar類型。到此多列合并問題完美解決。