【发布时间】:2019-09-07 06:45:44
【问题描述】:
我正在使用存储过程来完成更新查询,并且我已将消息框设置为在查询成功执行时显示。当我单击按钮时,会弹出消息框,但表格未更新。我在 SQL Server 中运行相同的查询,它更新了表,但无法通过 c# 更新
我已经在 SQL Server 中尝试过相同的代码,代码运行良好。命令执行时弹出消息框
if (IsUpdate)
{
MessageBox.Show("Clicked");
txtCustomerName.Enabled = false;
using (SqlConnection con = new SqlConnection(ApplicationSettings.ConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("usp_customer_updateProducts", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Contact", Contact);
cmd.Parameters.AddWithValue("@Address", address);
cmd.Parameters.AddWithValue("@PAN", PAN);
cmd.Parameters.AddWithValue("@VAT", VAT);
cmd.Parameters.AddWithValue("@CustomerName", CustomerName);
con.Open();
try
{
MessageBox.Show(CustomerName);
cmd.ExecuteNonQuery();
MessageBox.Show("Customer Updated Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
CustomerRecordForm crf = new CustomerRecordForm();
crf.Show();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
con.Close();
}
}
}
}
这里是存储过程的代码:
ALTER procedure [dbo].[usp_customer_updateProducts]
(
@Contact varchar,
@Address varchar,
@PAN varchar,
@VAT varchar,
@CustomerName varchar
)
as
begin
update [dbo].[CustomerInfo]
set [ContactNo]=@Contact,
[Address]=@Address,
[PAN]=@PAN,
[VAT]=@VAT
where [CustomerID] = (select CustomerID from CustomerInfo where CustomerName=@CustomerName)
end
【问题讨论】:
-
将其更改为
WHERE [CustomerId] IN ( SELECT CustomerId FROM... )而不是WHERE [CustomerId] = ( SELECT CustomerId FROM ... )。 -
仍然遇到同样的错误
-
也就是说,您可能需要考虑将存储过程的
UPDATE查询更改为使用INNER JOIN而不是WHERE IN,或者使用初始查询来设置@customerId变量,因为这可能更容易理解,并让您指出错误情况,其中有 0 行或多于 1 行匹配`@CustomerName`。 -
但我在同一张表中有记录,所以为什么要使用内连接
-
你为什么要查找
CustomerID?如果这是您的表的主键,那么您应该将@CustomerID传递到您的存储过程中。传入@CustomerName并在执行时进行查找可能会导致两行(或更多)行出现相同的信息。
标签: c# sql-server database