2

在我的网络应用程序中,我有一个搜索框,以便我可以使用名字或姓氏搜索我的数据库,它将在我的网络应用程序中显示结果。用户输入名字或姓氏。如果按名字查询搜索运行正常,但如果用户仅按姓氏搜索它显示表中的所有数据不显示像姓氏这样的数据

 string sql = @"SELECT opd_id AS [OPD No]
       , opd_date AS DATE
       , opd_dpt AS DEPARTMENT
       , opd_pfname + ' ' + opd_plname AS [Patient NAME]
       , opd_age AS AGE
       , opd_gender AS GENDER
       , opd_mob AS [MOBILE NO]
       , opd_fthrname AS [FATHER NAME]
       , opd_hsbndname AS [HUSBAND NAME]
       FROM tbl_OPD 
        WHERE opd_pfname like'%" + fname + @"%' 
        OR opd_plname like'%" + lname + @"% '
        ORDER BY DATE DESC";
4

2 回答 2

2

额外的空白区域

OR opd_plname like'%" + lname + @"% '

空白^

另外,请注意sql injection,您可以使用准备好的 sql 语句和参数绑定来修复它

于 2013-03-23T06:49:56.633 回答
1

如果没有看到更多代码,可能是您只填充了fnameor变量中的一个。lname假设是这种情况,您可以使用此代码。

// this assumes that you have only have 1 input for both the first name and lastname 
// and are storing it in a variable named searchForName
using (var connection = new SqlConnection("YOUR_CONFIGURATION_CONNECTION_STRING"))
{
    using (var command = new SqlCommand("SELECT opd_id AS [OPD No], opd_date AS DATE, opd_dpt AS DEPARTMENT, opd_pfname + ' ' + opd_plname AS [Patient NAME], opd_age AS AGE, opd_gender AS GENDER, opd_mob AS [MOBILE NO], opd_fthrname AS [FATHER NAME], opd_hsbndname AS [HUSBAND NAME] FROM tbl_OPD WHERE (opd_pfname like @p0 OR opd_plname like @p0) ORDER BY DATE DESC", connection))
    {
        command.Parameters.Add(new SqlParameter("@p0", string.Format("%{0}%", searchForName)));

        // rest of your code here E.G., sComm.ExecuteNonQuery();
    }
}

如果您知道两个变量都已填充,请尝试此代码块

using (var connection = new SqlConnection("YOUR_CONFIGURATION_CONNECTION_STRING"))
{
    using (var command = new SqlCommand("SELECT opd_id AS [OPD No], opd_date AS DATE, opd_dpt AS DEPARTMENT, opd_pfname + ' ' + opd_plname AS [Patient NAME], opd_age AS AGE, opd_gender AS GENDER, opd_mob AS [MOBILE NO], opd_fthrname AS [FATHER NAME], opd_hsbndname AS [HUSBAND NAME] FROM tbl_OPD WHERE (opd_pfname like @p0 OR opd_plname like @p1) ORDER BY DATE DESC", connection))
    {
        command.Parameters.Add(new SqlParameter("@p0", string.Format("%{0}%", searchForFirstName)));
        command.Parameters.Add(new SqlParameter("@p1", string.Format("%{0}%", searchForLastName)));

        // rest of your code here E.G., sComm.ExecuteNonQuery();
    }
}

PS。正如其他人所说,此处显示的代码有些不安全,您应该尽一切努力避免 Sql Injection 攻击。

于 2013-03-23T06:51:58.480 回答