2013-05-09 49 views
0

我创建了一个存储过程,它搜索的输入来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(); 

      } 
     } 

如何修改这个让搜索变得更加灵活。

回答

0

您可以使用SQL通配符与LIKE操作。

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

会给你以'P'开头的所有匹配结果。 %将替代数据库中的所有匹配字符。

select * from yourTable where yourColumn= 'P%' 

它也建议您搜索字符串大/小写发送到您的存储过程。然后,您可以uppercas/SQL查询小写的数据库列以及

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

因此搜索 'P%' 或 'P%' 将产生相同的结果