Gridview搜索

时间:2013-05-09 08:53:12

标签: c# stored-procedures gridview

我创建了一个基于输入搜索gridview的存储过程,如下所示:

Create procedure spSearch
( 
@Emp_id nvarchar(50) = null,
@Emp_name nvarchar(50) = null,
@Emp_exp nvarchar(50) = null,
@Emp_address nvarchar(50) = null
) 
AS 
BEGIN

If @Emp_id is not null and Len(@Emp_id )=0 Set @Emp_id = null
If @Emp_name is not null and Len(@Emp_name )=0 Set @Emp_name = null
If @Emp_exp is not null and Len(@Emp_exp )=0 Set @Emp_exp = null
If @Emp_address is not null and Len(@Emp_address )=0 Set @Emp_address = null

Select *
From tbl_employee
Where 
(@Emp_id is null or Emp_id Like @Emp_id )
and ( @Emp_name is null or Emp_name Like @Emp_name )
and ( @Emp_exp is null or Emp_exp Like @Emp_exp )
and ( @Emp_address is null or Emp_address Like @Emp_address )
END

但是,仅当输入与已存储的数据完全匹配时,此返回才是搜索项。

Eg : In tbl_employee I have 
Emp ID = 1
Emp_name = peter
Emp_exp = 2 years
Emp_address = xyz

只有当我输入Emp_name作为“peter”时,才会在gridview中填充搜索结果。 我需要修改存储过程,这样即使我在文本框中输入“pe”,也应该填充包含“pe”的所有数据。

这是c#代码:

private DataTable Search()
           {

               DataTable SearchResultsTable = new DataTable();

                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);


           try
              {

              SqlCommand cmd = new SqlCommand("spSearch", conn);
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.Parameters.AddWithValue("@Emp_id", txtEmpID.Text);
              cmd.Parameters.AddWithValue("@Emp_name" , txtEmpName.Text);
              cmd.Parameters.AddWithValue("@Emp_exp " , txtEmpExp.Text);
              cmd.Parameters.AddWithValue("@Emp_address " , txtEmpAddress.Text);
              SqlDataAdapter adapter = new SqlDataAdapter(cmd);
              adapter.Fill(SearchResultsTable);

               }

            catch (Exception ex)
                {
                   Response.Write(ex.ToString());
                }

                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }

                return SearchResultsTable ;
            }

        protected void  btnSearch_Click(object sender, EventArgs e)
            {

            EmployeeGridView.DataSource = Search();
            EmployeeGridView.DataBind();

            }
        }

如何修改此搜索以使搜索变得更加灵活。

2 个答案:

答案 0 :(得分:0)

您可以在程序中使用外卡来达到您的要求

请看看这个

stored procedure with wildcard parameters

答案 1 :(得分:0)

您可以将SQL通配符与LIKE运算符一起使用。

and ( @Emp_name is null or Emp_name Like @Emp_name )+ '%'

将为您提供以“P”开头的所有匹配结果。 %将替换数据库中的所有匹配字符。

select * from yourTable where yourColumn= 'P%'

建议将搜索字符串大写/小写发送到存储过程。然后,您也可以在SQL查询中高举/小写数据库列

select * from yourTable where UPPER(yourColumn)= 'P%'
  

因此,搜索“p%”或“P%”会产生相同的结果