我们的c#中经常用到了switch case,那么在sql中是否也有这样的一种格式或者是功能呢?
CASE WHEN 是sql server中的重要关键字之一,也许你对他有很多的理解,但是他真的有很多的用法,今天我就来向大家介绍一种。
实现简单的搜索功能;
数据库中的表:
现在我们要实现根据专业看各个学院有多少的人。
case when 语句:
实现的效果:
由于我的这个例子数据量很小,所以好像看不出来他的优势。但是这个例子很简单的让我们都了解了他的最基本的语法结构。
当我们的数据量很大,用我们的机房的那种一句sql语句打开一个sqlhelper的方法速度就会很慢的。而用它可以大大的减少时间。
在NCRE中,更新分数和考生答题记录,师哥就是用的这种方法。这是一个D层的代码:
<span style="font-size:18px;"> public void ReturnScore(List<IEQuestionRecordEntity> list, IEQuestionRecordEntity studentrecord)
{
String which = WhichIERecored(studentrecord);
StringBuilder sbSql = new StringBuilder();
sbSql.Append(" update IEQuestionRecordEntity_" + which + " SET fraction = CASE questionID ");
string Fation = string.Empty;
string questionID = string.Empty;
string studentIDs = string.Empty;
string tamstamp = string.Empty;
//根据学号,和时间戳选出这一段的内容,然后再根据QuestionID给每一个flag更新分数。
#region 更新分数的拼接sql语句
for (int i = 0; i < list.Count; i++)
{
questionID = list[i].questionID.ToString();
//将分数传给变量
Fation = list[i].fraction.ToString();
//判分sql,拼接sql,用case,when语句
sbSql.Append(" WHEN '" + questionID + "' THEN '" + Fation + "'");
}
sbSql.Append(" end,"); //加“,”
#endregion
#region 拼接考生答案更新到数据库中
//拼接更新考生答案sql
sbSql.Append(" examAnswer = CASE questionID");
for (int i = 0; i < list.Count; i++)
{
string examAnswer = list[i].examAnswer.ToString();
questionID = list[i].questionID.ToString();
//学生答案信息更新,when后边的是QuerstionID,
sbSql.Append(" WHEN '" + questionID + "' THEN '" + list[i].examAnswer + "'");
}
sbSql.Append(" end"); //不加逗号“,”
#endregion
studentIDs += "'" + list[0].studentID.ToString() + "'";
tamstamp += "'" + list[0].timeStamp.ToString() + "'";
studentIDs.Remove(studentIDs.Length - 1, 1);
sbSql.Append(" where studentID in (" + studentIDs + ") and timeStamp in (" + tamstamp + ")");
DataTable dt = sqlhelper.ExecuteQuery(sbSql.ToString(), CommandType.Text);
}</span>
利用循环和CASE WHEN,解决了多次打开SQLHelper的问题。
SQL 提供了巨大的语句,给我们的代码带来了更大程度上的方便。