if (allStatusCheckBox.Checked != true)
{
if (assComboBox.SelectedIndex != -1 && revComboBox.SelectedIndex != -1)
{
dataSda = new SqlDataAdapter("SELECT DATAACTUALID WHERE ASSIGNEDSTATUS LIKE '" + statusComboBox.SelectedValue + "' AND A_ASSIGNEDTO.EMP_ID LIKE '" + assComboBox.SelectedValue + "%' AND A_TOBEREVIEWEDBY.EMP_ID LIKE '" + revComboBox.SelectedValue + "%'", patientCon);
}
else if (assComboBox.SelectedIndex != -1 && revComboBox.SelectedIndex == -1)
{
dataSda = new SqlDataAdapter("SELECT DATAACTUALID WHERE ASSIGNEDSTATUS LIKE '" + statusComboBox.SelectedValue + "' AND A_ASSIGNEDTO.EMP_ID LIKE '" + assComboBox.SelectedValue + "%'", patientCon);
}
else if (assComboBox.SelectedIndex == -1 && revComboBox.SelectedIndex != -1)
{
dataSda = new SqlDataAdapter("SELECT DATAACTUALID WHERE ASSIGNEDSTATUS LIKE '" + statusComboBox.SelectedValue + "' AND A_TOBEREVIEWEDBY.EMP_ID LIKE '" + revComboBox.SelectedValue + "%'", patientCon);
}
else
{
dataSda = new SqlDataAdapter("SELECT DATAACTUALID WHERE ASSIGNEDSTATUS LIKE '" + statusComboBox.SelectedValue + "'", patientCon);
}
}
else
{
//REPEAT WITHOUT STATUSCOMBOX.SELECTED VALUE
}
该代码的主要目的是根据是否已应用某些过滤器来显示一些信息。但是,按照我目前的方法,每次我应用新的过滤器时,if语句的数量都呈指数增长。我担心随着我应用更多过滤器,我的代码很快就会变得缓慢且难以管理。有没有更好的方法来达到相同的结果?
答案 0 :(得分:1)
在担心某些if
语句之前,您的代码有很多更大的问题。我将解决所有这些问题,您将开始看到修复它们,将修复您的混乱情况。
首先,您的所有查询中的SQL查询文本基本上相同:
SELECT
DATAACTUALID,
A_DATAACTUAL.TRIGGERPOINTSID,
TBLPT.PT_ID,
NAME as C,
A_ASSIGNEDTO.EMP_ID as ASSIGNEDID,
A_TOBEREVIEWEDBY.EMP_ID as REVIEWERID,
TBLPT.LASTNAME + ' ' + TBLPT.FIRSTNAME as Patient,
TRIGGERNAME as DESCRIPTION,
TRIGGERPOINTNAME as DETAIL,
A_ASSIGNEDTO.EMP_LASTNAME + ' ' + A_ASSIGNEDTO.EMP_FIRSTNAME as Assigned,
TODOBY, A_TOBEREVIEWEDBY.EMP_LASTNAME + ' ' + A_TOBEREVIEWEDBY.EMP_FIRSTNAME as Reviewer,
REVIEWDATE,
GRADE,
COMMENT
FROM A_DATAACTUAL
INNER JOIN TBLPT ON A_DATAACTUAL.PT_ID = TBLPT.PT_ID
INNER JOIN A_TRIGGERPOINTS ON A_DATAACTUAL.TRIGGERPOINTSID = A_TRIGGERPOINTS.TRIGGERPOINTSID
INNER JOIN A_TRIGGERS ON A_TRIGGERPOINTS.TRIGGERID = A_TRIGGERS.TRIGGERID
INNER JOIN A_ASSIGNEDTO ON A_DATAACTUAL.ASSIGNEDTO = A_ASSIGNEDTO.EMP_ID
INNER JOIN A_TOBEREVIEWEDBY ON A_DATAACTUAL.TOBEREVIEWEDBY = A_TOBEREVIEWEDBY.EMP_ID
INNER JOIN A_STATUS ON A_DATAACTUAL.ASSIGNEDSTATUS = A_STATUS.STATUSID
您看到所有这些联接和特定的选择/别名吗?这是创建SQL View的 prime 机会,然后您可以查询该新创建的View,而不必一遍又一遍地不断进行相同的精确查询。
假设您命名了视图v_SomeView
,所有查询都将如下所示:
"SELECT * FROM v_SomeView WHERE A_ASSIGNEDTO.EMP_ID LIKE ..."
"SELECT * FROM v_SomeView WHERE A_TOBEREVIEWEDBY.EMP_ID LIKE ..."
使用SQL的强大功能,C#应该只负责这么多...
第二个大问题是您具有SQL Injection漏洞。您应该从不连接这样的SQL查询。 始终使用参数。
如果必须使用SqlDataAdapter
的简单示例:
dataSda = new SqlDataAdapter("SELECT * FROM v_SomeView WHERE ASSIGNEDSTATUS = @someValue", patientCon);
dataSda.SelectCommand.Parameters.Add(new SqlParameter("@someValue", assComboBox.SelectedValue));
通过这两个更改,您使代码更安全,使它保持DRY并利用了SQL的功能。