我有一个通用的更新函数,它接受一个数据表,选择查询,并使用它来更新数据库tables.It工作得很好。我需要知道是否有一种方法可以通过更改以下代码来恢复插入行的ID (identity字段)。
Public Function UpdateDataTable_GetID(ByVal dt As DataTable, ByVal SQL As String, ByVal connString As String) As Integer
Dim conn As SqlConnection = Nothing
Dim cmd As SqlCommand
Dim adp As SqlDataAdapter = Nothing
Dim cmdBuilder As SqlCommandBuilder = Nothing
Dim UpdatedID As Integer
If SQL.Length <= 0 Then
Return False
End If
conn = New Data.SqlClient.SqlConnection(connString)
cmd = New Data.SqlClient.SqlCommand
cmd.Connection = conn
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
adp = New Data.SqlClient.SqlDataAdapter(cmd)
cmdBuilder = New Data.SqlClient.SqlCommandBuilder(adp)
Try
UpdatedID = Convert.ToInt32(adp.Update(dt)) ' What to do here to get the just inserted ID instead of number of records updated
adp.Dispose()
cmdBuilder.Dispose()
Return UpdatedID
Catch ex As System.Data.SqlClient.SqlException
' Closing connection
Return -1
Finally
End try
End function我知道一些解决方案,在这些解决方案中,我可以使用设计器将"select scope_identity()“附加到数据适配器查询的插入命令中,并编辑适配器的插入命令文本,然后执行ExecuteScalar()。我想知道是否可以调整通用适配器.Update()以获得插入行的ID。
发布于 2016-08-29 21:35:33
你可以用这样的代码订阅这个事件:(C# I know VB)
adp.RowUpdated += adapter_RowUpdated;并自己编写事件:
void adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
if (e.StatementType == StatementType.Insert)
{
object id = e.Command.Parameters["@ID"].Value;
e.Row[_identityFieldName] = id;
}
}在本例中,首先将以下内容添加到命令文本中:
SET @ID = SCOPE_IDENTITY() 并且已经填充了私有变量_identityFieldName。
也许这能帮到你。
编辑:我注意到您还使用了SqlCommandBuilder,这使得添加作用域标识变得更容易:
SqlCommand inserter = new SqlCommand();
inserter = cmdBuilder.GetInsertCommand(true).Clone();
inserter.CommandText += " SET @ID = SCOPE_IDENTITY()";
SqlParameter param = new SqlParameter();
param.Direction = ParameterDirection.Output;
param.Size = 4;
param.DbType = DbType.Int32;
param.ParameterName = "@ID";
inserter.Parameters.Add(param);
adp.InsertCommand = inserter;https://stackoverflow.com/questions/39205916
复制相似问题