我正在插入一行并使用ADO.Net返回id号: -
command_string = "INSERT INTO [MyDB].[dbo].[MyTable] (THIS, THAT)" & _
" OUTPUT inserted.ID_NUMER AS ID_NUMBER " & _
" VALUES ('This', 'That')"
Dim insert_command As SqlCommand =
New SqlCommand(command_string, database_connection)
Dim output_parameter As SqlParameter =
New SqlParameter("@id_number", SqlDbType.Int)
Dim transaction As SqlTransaction =
database_connection.BeginTransaction(System.Data.IsolationLevel.Serializable)
insert_command.Transaction = transaction
output_parameter.Direction = ParameterDirection.Output
insert_command.Parameters.Add(output_parameter)
insert_command.ExecuteNonQuery()
Dim reader As SqlDataReader = insert_command.ExecuteReader()
reader.Read()
id_number = reader.GetInt32(0)
reader.Close
transaction.Commit
但执行时此代码会在目标表中插入两行。从阅读器返回的id_number
是第二行的ID号。
有谁知道为什么要插入两行,我该怎么办呢? (我已经检查了这个问题here,我不认为这是同一个问题,但我可以确认代码只执行一次而且表没有触发器。)
答案 0 :(得分:4)
因为你执行了两次
insert_command.ExecuteNonQuery()
Dim reader As SqlDataReader = insert_command.ExecuteReader()
所以删除第一个并保持:
Dim reader As SqlDataReader = insert_command.ExecuteReader()
答案 1 :(得分:2)
要获取您的ID_Number,请尝试使用ExecuteScalar:
id_number = insert_command.ExecuteScalar()
无需致电ExecuteReader
或ExecuteNonQuery
。