执行 SQL Server 事务时如何防止出现以下错误?
我正在尝试将 aSupplierOrder
和 a添加VehicleRecord
到一组两个数据库表中。我正在使用以下内容:
表 SQL 结构:
CREATE TABLE VSI_VehicleRecords
(
VehicleRecordID INT IDENTITY(1,1) PRIMARY KEY,
StockNumber INT NOT NULL,
Status INT NOT NULL,
Make VARCHAR(50) NOT NULL,
Model VARCHAR(50) NOT NULL,
Colour VARCHAR(50) NOT NULL,
Spefication VARCHAR(255) NOT NULL
)
CREATE TABLE VSI_SupplierOrders
(
SupplierOrderID INT IDENTITY(1,1) PRIMARY KEY,
VehicleRecordID INT FOREIGN KEY REFERENCES VSI_VehicleRecords(VehicleRecordID) UNIQUE,
Timestamp
)
我编写了一个实用方法,它将一组 Sql 查询作为事务运行:
C# 执行事务:
SqlTransaction _Transaction;
OpenConnection();
_Transaction = __Connection.BeginTransaction();
try
{
for (int i = 0; i < Commands.Length; i++)
{
Commands[i].Connection = __Connection;
Commands[i].Transaction = _Transaction;
Commands[i].ExecuteNonQuery();
}
_Transaction.Commit();
return true;
}
catch (SqlException e)
{
_Transaction.Rollback();
}
上述函数要执行的SQL命令:
SqlCommand[] _Commands = new SqlCommand[2];
string _InsertVehicleQuery = "INSERT INTO VSI_VehicleRecords(StockNumber,Status,Make,Model,Colour,Spefication) VALUES (@StockNumber, @Status, @Make, @Model, @Colour, @Specification);";
SqlCommand _InsertVehicleCommand = new SqlCommand(_InsertVehicleQuery);
_InsertVehicleCommand.Parameters.AddWithValue("@StockNumber", __StockNumber);
_InsertVehicleCommand.Parameters.AddWithValue("@Status", __Status);
_InsertVehicleCommand.Parameters.AddWithValue("@Make", Make);
_InsertVehicleCommand.Parameters.AddWithValue("@Model", Model);
_InsertVehicleCommand.Parameters.AddWithValue("@Colour", Colour);
_InsertVehicleCommand.Parameters.AddWithValue("@Specification", Specification);
_Commands[0] = _InsertVehicleCommand;
string _InsertSupplierOrderQuery = "INSERT INTO VSI_SupplierOrders(VehicleRecordID) VALUES (@VehicleRecordID);";
SqlCommand _InsertSupplierOrderCommand = new SqlCommand(_InsertSupplierOrderQuery);
_InsertSupplierOrderCommand.Parameters.AddWithValue("@VehicleRecordID", _VehicleRecordID);
_Commands[1] = _InsertSupplierOrderCommand;
DataUtility.NonQueryTransaction(_Commands);
但是我收到以下错误:
*INSERT 语句与 FOREIGN KEY 约束“FK__VSI_Suppl_ Vehic _5165187F”冲突。冲突发生在数据库“jack_test”、表“dbo.VSI_VehicleRecords”、列“VehicleRecordID”中。*