我有一个存储过程,可以在单击按钮时执行搜索。搜索页面只是一个组合框和一个文本框。用户从要搜索的组合框中选择列,然后在文本框中输入值。不管从组合框中选择哪个值,该存储程序都可以在第一次尝试时很好地执行。随后点击搜索按钮都会给我“参数过多”错误。
C#
public partial class InitialDebt : Form
{
static string conn = System.Configuration.ConfigurationManager.ConnectionStrings["myConnStr"].ConnectionString;
static SqlConnection misc = new SqlConnection(conn);
static SqlCommand initDebt = misc.CreateCommand();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(initDebt);
static int index = 0;
public InitialDebt()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (ddlFilter.Text == "SELECT")
{
MessageBox.Show("Please select a value from the drop down list");
}
else
{
try
{
string Filter = ddlFilter.Text;
string SearchStr = txtSearchStr.Text;
initDebt.CommandType = CommandType.StoredProcedure;
initDebt.CommandText = "mySPROC";
initDebt.Parameters.Add("@Filter", SqlDbType.VarChar).Value = Filter;
initDebt.Parameters.Add("@SearchStr", SqlDbType.VarChar).Value = SearchStr;
da.Fill(dt);
misc.Open();
txtSS.Text = dt.Rows[0]["SS_Num"].ToString();
txtLName.Text = dt.Rows[0]["last_Name"].ToString();
txtFName.Text = dt.Rows[0]["first_name"].ToString();
txtAgt.Text = dt.Rows[0]["agent_num"].ToString();
txtStore.Text = dt.Rows[0]["agent_name"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("There are no records that match your search criteria. " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
misc.Close();
}
}
}
我尝试过:
SQL
@Filter varchar(20),
@SearchStr varchar(40)
AS
BEGIN
SELECT SS_Num, upper(Last_Name) as Last_name, upper(First_Name) as first_name,
upper(Address) as address, upper(City) as city, upper(State) as state,
Zip_code, upper(Agency_code) as agency_code, Agent_num,
upper(Agent_name) as agent_name, debt_date, debt_amount
FROM myTable
WHERE
(
CASE
WHEN @Filter = 'SS #' THEN SS_Num
WHEN @Filter = 'LAST NAME' THEN Last_Name
WHEN @Filter = 'CITY' THEN City
WHEN @Filter = 'AGENT #' THEN Agent_num
WHEN @Filter = 'STORE' THEN Agent_Name
END
like '%'+@SearchStr+'%'
)
END
预先感谢您的任何建议。
答案 0 :(得分:0)
在方法内部创建命令和连接,并在完成后处置它们。使用“ using”块会很好。
这也将解决您的“参数”问题,因为您将为每次新单击创建一个新的命令和连接对象。