sql >> Base de Datos >  >> RDS >> Sqlserver

Exportar Excel a SQL usando VBA

Aquí está el enfoque de parámetros:

Dim conn As ADODB.Connection
Dim cmd As ADODB.Command

Dim strSQL As String

strSQL = "INSERT INTO dbo.TimeLog " & _
    "(RecordedPeriod, EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) " & _
"VALUES (?,?,?,?,?,?,?,?);"

Set conn = New ADODB.Connection
conn.Open ""Provider=SQLOLEDB;Data Source=db1\db1;Initial Catalog=ProdTrack;Integrated Security=SSPI;"
'Skip the header row
iRowNo = 2"

Set cmd = New ADODB.Command

cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = strSQL

iRowNo = 2

With Sheets("Sheet1")
  'Loop until empty cell in FirstName
  Do Until .Cells(iRowNo, 1) = ""

  cmd.Parameters.Append _
    cmd.CreateParameter("pRecordedPeriod", adDBTimeStamp, adParamInput, 8, .Cells(iRowNo, 1))
  cmd.Parameters.Append _
    cmd.CreateParameter("pEventDate", adVarChar, adParamInput, 8, .Cells(iRowNo, 2))
  cmd.Parameters.Append _
    cmd.CreateParameter("pID", adInteger, adParamInput, , .Cells(iRowNo, 3))
  cmd.Parameters.Append _
    cmd.CreateParameter("pDeptCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 4))
  cmd.Parameters.Append _
    cmd.CreateParameter("pOpCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 5))
  cmd.Parameters.Append _
    cmd.CreateParameter("pStartTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 6))
  cmd.Parameters.Append _
    cmd.CreateParameter("pFinishTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 7))
  cmd.Parameters.Append _
    cmd.CreateParameter("pUnits", adInteger, adParamInput, , .Cells(iRowNo, 8))

  cmd.Execute

  iRowNo = iRowNo + 1
  Loop
End With

conn.Close
Set conn = Nothing

el DataTypeEnum

Pero esto no es agradable de codificar, en comparación con una consulta de parámetros DAO. Sin parámetros con nombre, cinco parámetros para configurar. Esto es para Stored Procedures ? Para CRUD esto no es divertido.