2013-05-09 60 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%' 將產生相同的結果