Visual Basic.NET - Hacer un Select dentro de una transaccion

 
Vista:

Hacer un Select dentro de una transaccion

Publicado por Helmer (4 intervenciones) el 26/11/2011 06:19:20
Hola Amigos, tengo una transaccion dentro del cual voy a insertar datos en varias tablas diferentes pero al momento de grabar UN REGISTRO EN UNA TABLA, necesito obtener el ultimo numero del ultimo registro y asi sumarle una unidad y grabar el nuevo registro con el nuevo numero.
me explico mejor con el siguiente codigo de ejemplo:

'''************************************
'
Function InsertarDatos(ByVal cn As SqlConnection, ByVal strError As String, ByVal Fecha_Sol As Date, ByVal Nro_Sol As Integer, ByVal Ruc As String, ByVal Fecha_Reg As Date, ByVal Comprobante As String, ByVal Glosa As String, ByVal Documentos As Boolean) As Boolean
Dim Fila As Integer
Dim cm As New SqlCommand
InsertarDatos = False
Dim Orden As Integer
Dim NroCot As String
cn.Open()
Dim DTabla As New DataTable
'INICIO LA TRANSACCION
Dim transaccion As SqlTransaction
transaccion = cn.BeginTransaction

Try

For Fila = 0 To DGProveedores.RowCount - 1

''ESTA ES LA CONSULTA DONDE QUIERO OBTENER EL NRO DE ORDEN HABIENDO YA INICIADO LA TRANSACCION

Dim objqNroOrden As New PakInfor.qrSolici
Orden = objqNroOrden.ObtenerNroOrden(cn, strError, Fecha_Sol, Nro_Sol)
objqNroOrden = Nothing

'AQUI OCURRE LO MISMO, NECESITO EN CORRELATIVO PARA EL NRO DE COTIZACIONES
Dim objqNroCot As New PakInfor.qrSolici
NroCot = objqNroCot.ObtenerNroCotizacion(cn, strError, Fecha_Reg)
objqNroCot = Nothing

'AQUI INSERTO EL VALOR DE LA VARIABLE QUE RETORNA LA CONSULTA
cm.CommandText = " insert into log_Detalle_Registro(Fecha_Sol,Nro_Sol,RUC,Fecha_Reg,Comprobante,Orden,Glosa)" & _
" values('" & FechaSQL(Fecha_Sol) & "'," & Nro_Sol & ", '" & CStr(DGProveedores.Rows(Fila).Cells("RUC").Value) & "','" & FechaSQL(Fecha_Reg) & "','" & Comprobante & "'," & Orden & ",'" & Glosa & "')"
cm.ExecuteNonQuery()
cm.CommandText = " insert into log_Cotización(FechaCot,NroCot,RUC,Documentos,Fecha_Sol,Nro_Sol,Estado) " & _
" values ('" & FechaSQL(Fecha_Reg) & "','" & NroCot & "','" & CStr(DGProveedores.Rows(Fila).Cells("RUC").Value) & "'," & CInt(Documentos) * -1 & ",'" & FechaSQL(Fecha_Sol) & "'," & Nro_Sol & ",'P')"
cm.ExecuteNonQuery()

cn.Close()
Next
cm.CommandText = "update Log_Cuadro_Adquisición set Estado='2' " & _
" FROM LOG_CUADRO_ADQUISICIÓN C INNER JOIN LOG_SOLICITUD_COTIZACIóN S " & _
" ON C.FECHA=S.FECHA AND C.NRO=S.NRO " & _
" WHERE FECHA_SOL='" & FechaSQL(Fecha_Sol) & "' AND NRO_SOL=" & Nro_Sol
cm.ExecuteNonQuery()
transaccion.Commit()
InsertarDatos = True

Catch EX As Exception
transaccion.Rollback()
Dim MENSAJE As String
MENSAJE = EX.Message
MsgBox(MENSAJE, CType(16, MsgBoxStyle), "Error")
cn.Close()
InsertarDatos = False
End Try
cn.Close()
End Function


'**********************************************

Public Function ObtenerNroOrden(ByVal cn As SqlConnection, ByVal strError As String, ByVal Fecha_Sol As Date, ByVal Nro_Sol As Integer) As Integer
Dim strConsulta As String
ObtenerNroOrden = -1
Dim DTabla As New DataTable()

Try
strConsulta = "select top 1 Orden from log_Detalle_Registro where Fecha_Sol='" & FechaSQL(Fecha_Sol) & "' and Nro_Sol=" & Nro_Sol & " " & _
" order by orden desc"
Dim CMD As New SqlDataAdapter(strConsulta, cn)


''AQUI SALE EL ERROR
'------------------------------------------------------
CMD.Fill(DTabla)
''-------------------------------------------------
If DTabla.Rows.Count = 0 Then
ObtenerNroOrden = 1
Else
ObtenerNroOrden = CInt(DTabla.Rows(0).Item("Orden")) + 1
End If

Catch ex As Exception

MsgBox(Now & ex.Message, MsgBoxStyle.Critical)

End Try
Return ObtenerNroOrden
End Function


'**************************************
Las instrucciones anteriores, me dan un error al ejecutar las consultas;

EXECUTEREADER REQUIERE QUE EL COMANDO TENGA UNA TRANSACCION CUANDO LA CONEXION ASIGNADA AL MISMO ESTA EN UNA TRANSACCION LOCAL PENDIENTE. NO SE HA INICIALIZADO LA PROPIEDAD TRANSACTION DEL COMANDO.

POR FAVOR, ESTO SOLIA HACERLO EN VB 6.0 PERO AHORA EN VS 2010 NO SE COMO HACERLO.
GRACIAS.

nota: la consulta necesariamente tiene que estar dentro de la transaccion, porque cuando esta fuera de ella corre sin ningun problema, pero no me sirve de nada.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder