我想更新数据库的一行。
这是一台ATM机,您首先输入一个卡帐号(它保存此号码以用于不同的表格)。然后输入存款金额。问题是它正在更新每一行而不是与该卡相关联的单行。
以下是代码:
sqlCommandDeposit.Connection.Open();
sqlCommandDeposit.Parameters["@cardNumber"].Value = Class1.cardNumber;
using (SqlDataReader reader = sqlCommandDeposit.ExecuteReader())
{
if (reader.Read())
{
balanceDB = decimal.Parse(reader["balance"].ToString());
}
}
}
finally
{
sqlCommandDeposit.Connection.Close();
}
decimal depositAmm = Convert.ToDecimal(textDeposit.Text);
balanceDB = balanceDB + depositAmm;
try
{
sqlDepositupdate.Connection.Open();
sqlDepositupdate.Parameters["@cardNumber"].Value = Class1.cardNumber;
sqlDepositupdate.Parameters["@balanceDB"].Value = balanceDB;
sqlDepositupdate.ExecuteNonQuery();
MessageBox.Show("£" + depositAmm + " Successfully Deposited and Deposit Number Saved");
MessageBox.Show("you have " + "£" + balanceDB + " available");
buttonClear.Enabled = true;
buttonExit.Enabled = true;
buttonMainMenu.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sqlDepositupdate.Connection.Close();
}
这是我的选择陈述,以找出当前的余额:
SELECT dbo.Accounts.balance
FROM dbo.ATMCards
INNER JOIN dbo.Accounts ON dbo.ATMCards.accountID = dbo.Accounts.accountID
WHERE (dbo.ATMCards.cardNumber = @cardNumber)
这是更新声明:
UPDATE dbo.Accounts
SET balance = @balanceDB
FROM dbo.ATMCards
INNER JOIN dbo.Accounts AS Accounts_1 ON dbo.ATMCards.accountID = Accounts_1.accountID
CROSS JOIN dbo.Accounts
WHERE (dbo.ATMCards.cardNumber = @cardNumber)
答案 0 :(得分:6)
在更新查询中删除交叉连接。你为什么这么做?
UPDATE dbo.Accounts
SET balance = @balanceDB
FROM dbo.ATMCards
INNER JOIN dbo.Accounts AS Accounts_1 ON dbo.ATMCards.accountID = Accounts_1.accountID
WHERE (dbo.ATMCards.cardNumber = @cardNumber)
答案 1 :(得分:1)
更新语句的问题是加入表的方法,CROSS JOIN
将一个表中的所有行与另一个表中的所有行连接起来,因此更新将影响所有行中的所有行。表,尽管你的WHERE
条款。 CROSS JOIN
也称为笛卡尔积。
建议您修改更新声明。