运行测试以插入帐户时,我偶然发现错误:
“违反了主键约束'PK_dbo.Accounts'。无法在对象'dbo.Accounts'中插入重复的键。”
我知道即时消息正在插入重复项,但我不知道该如何解决。我已经尝试使用scope_identity,但是我不确定即时通讯是否正确使用它。
PS:我无法更改数据库。
private static SqlCommand CreateInsertCommand(Account account, SqlConnection connection)
{
string insertStatement =
"SET IDENTITY_INSERT Accounts ON " +
"INSERT INTO Accounts " +
"(Id, AccountNumber, Balance, AccountType, CustomerId) " +
"VALUES (@Id, @AccountNumber, @Balance, @AccountType, @CustomerId) " +
"SELECT SCOPE_IDENTITY() " + // gets id from inserted account
"SET IDENTITY_INSERT Accounts OFF";
SqlCommand insertCommand = new SqlCommand(insertStatement, connection);
if (account.Id == 0)
{
insertCommand.Parameters.AddWithValue("@Id", account.Id);
}
答案 0 :(得分:0)
也许您只是想update
?
update accounts
set AccountNumber = @AccountNumber,
Balance = @Balance,
AccountType = @AccountType,
CustomerId = @CustomerId
where id = @id;
答案 1 :(得分:0)
IDENTITY_INSERT
允许您为通常自动生成的字段指定值。它不允许您创建重复项。
您需要先删除重复项,然后使用IDENTITY_INSERT指定所需的值-或仅编辑现有行。