問(wèn)題背景:
在做考試系統(tǒng)手動(dòng)生成試卷部分時(shí)由于題庫(kù)的表結(jié)構(gòu)不相同,導(dǎo)致同樣的Gridview(已模板化后的,其結(jié)構(gòu)已固定)在顯示時(shí)不能同時(shí)兩種不同結(jié)構(gòu)的數(shù)據(jù)。如GridView結(jié)構(gòu)如下所示:
這種固定的格式顯示的是以選擇題為代表的數(shù)據(jù)結(jié)構(gòu),但是因?yàn)檫x擇題題庫(kù)表結(jié)構(gòu)與論述題題庫(kù)表結(jié)構(gòu)不相同,所以無(wú)法直接顯示以論述題為代表的數(shù)據(jù)結(jié)構(gòu)。這時(shí)如何在這個(gè)固定的GridView中顯示不同的數(shù)據(jù)呢?其實(shí)在仔細(xì)觀察后我們可以發(fā)現(xiàn)他們唯一的區(qū)別在于“答案”這列的數(shù)據(jù)不同,在選擇題類型中,該字段的值僅為一個(gè)選項(xiàng)而已,但是對(duì)于論述題等類型,其問(wèn)題有六個(gè),對(duì)應(yīng)的答案也應(yīng)該有六列才對(duì)。分析到此,可以總結(jié)一下,最終要解決的問(wèn)題是如何將六列的答案顯示在一列。
解決辦法:將六個(gè)字段中的內(nèi)容用sql語(yǔ)句實(shí)現(xiàn)合并,將其作為一個(gè)新的字段顯示出來(lái),具體的實(shí)現(xiàn)請(qǐng)看代碼:
復(fù)制代碼 代碼如下:
#region 根據(jù)動(dòng)態(tài)生成的數(shù)據(jù)庫(kù)表名,從該表中選出QuestionId,ChapterId,QuestionTypeId,Point,不包括難度等級(jí)約束
/// summary>
/// 根據(jù)動(dòng)態(tài)生成的數(shù)據(jù)庫(kù)表名,從該表中選出QuestionId,ChapterId,QuestionTypeId,Point,
/// Degree,Fraction,QuestioinContent,IsValid等內(nèi)容,不包括難度等級(jí)約束
/// /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("從動(dòng)態(tài)生成的數(shù)據(jù)庫(kù)表中獲取QuestionId,ChapterId,QuestionTypeId,Point失?。ú话y度等級(jí))");
}
finally
{
sqlHelper.Close();
}
}
#endregion
其中使用cast函數(shù)的strSql語(yǔ)句所起到的作用就是將多個(gè)字段合并成一個(gè)新字段。另外需要注意的是strSql語(yǔ)句中的 “ + ” 號(hào),如果需要合并的字段的內(nèi)容是Text類型的,是不支持該符號(hào)的,這時(shí)我們需要將其轉(zhuǎn)換成nvarchar類型。到此多列合并問(wèn)題完美解決。