我创建了一个存储过程,它根据输入搜索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();
}
}
我该如何修改它以使搜索变得更加灵活。