我认为 ID 的 Maintainance 表应该是自动递增的。为了实现这一点,你可以设置 Is Identity 至 Yes
ID
Maintainance
Is Identity
Yes
在插入的最后,如果你想要ID,你可以得到
Select SCOPE_IDENTITY()
如果你想增加 ID 手动然后试试这个:
declare @newid int Select @newid = Max(ISNULL(MaintenanceNo, 0)) from Maintenance set @newid = @newid + 1
然后用 @newid 用于插入和最后 Select @newid
@newid
Select @newid
要解决您的问题,您只需更改一行并删除一堆不必要的代码
Dim cmd As SqlCommand = New SqlCommand() cmd.Connection = connection cmd.CommandType = CommandType.StoredProcedure cmd.CommandText = "Insert_Maintenance" .... you need to build the parameters collection here ..... Try connection.Open() Dim result = cmd.ExecuteScalar() ' <- Instead of ExecuteNonQuery ' if result IsNot Nothing Then Console.WriteLine("The Mno is:" & Convert.ToInt32(result) End If
的ExecuteScalar 返回结果中第一行的第一列。这应解决代码的VB.NET方面。当然,如果您不需要控制在MaintenanceNo列中插入的值,那么接下来要采取的操作是在字段属性中将Identity属性设置为Yes。通过这种方式,您可以删除存储过程的最后几行,并忘记为MaintenaceNo字段传递任何内容
INSERT INTO Maintenance(PlateNo, MaintenanceType, AutoCenterNo,MaintenanceDate, Qty, IndivisualVal, TotalVal, Notes) VALUES (@PlateNo, @MaintenanceType, (select AutoCenterNo from AutoCenter where Name = @Name), @MaintenanceDate, @Qty, @IndivisualVal, @TotalVal, @Notes) SELECT SCOPE_IDENTITY()