Почему Update Macro не обновляет мою SQL таблицу серверов - PullRequest
0 голосов
/ 02 марта 2020

У меня есть ниже функция и макрос. Цель макроса - обновить столбец в моей таблице SQL Server, используя значения из моего файла Excel на основе номера отгрузки. Когда я запускаю макрос, я не получаю никаких ошибок, и появляется окно сообщения о том, что была произведена строка, но когда я проверяю таблицу SQL Server, значение в этом столбце по-прежнему равно нулю.

Function mydbConnect() As Object

    Dim sConStr As String

    sConStr = "Provider=***;Password=***********;User ID=******;Initial Catalog=*******; Data Source=***************"

    Set mydbConnect = CreateObject("ADODB.Connection")
    mydbConnect.Open sConStr

End Function

Sub tableupdate2()
  Const COL_NUM As String = "A"
  Const COL_DATE As String = "K"
  Const TABLE As String = "dbo.cxu_all_load_control"

  ' define update sql
  Const SQL  As String = " UPDATE " & TABLE & _
                         " SET Driver_arr_dte = CAST(? AS DATETIME2) " & _
                         " WHERE mst_ship_num = ? "

  ' establish connection and create command object
  Dim con As Object, cmd As Object, sSQL As String
  Set con = mydbConnect() ' establish connection
  Set cmd = CreateObject("ADODB.Command")

  With cmd
    .ActiveConnection = con
    .CommandText = SQL
    .CommandType = 1 'adCmdText
    .Parameters.Append .CreateParameter("P1", adVarChar, 1, 20) '
    .Parameters.Append .CreateParameter("P2", adVarChar, 1, 50) ' adParamInput = 1
  End With

  ' prepare to get data from spreadsheet
  Dim wb As Workbook, ws As Worksheet, iLast As Integer, iRow As Integer
  Set wb = ThisWorkbook
  Set ws = wb.Sheets("Dwell Report")

  iLast = ws.Range(COL_NUM & Rows.count).End(xlUp).Row

  Dim p1 As String, p2 As String, count As Long

  ' scan sheet and update db
  Debug.Print "Updates " & Now

  With cmd
     For iRow = 5 To iLast
       p1 = Format(ws.Range(COL_DATE & iRow).Value, "yyyy-mm-dd hh:mm")
       p2 = ws.Range(COL_NUM & iRow).Value

       If Len(p2) > 0 Then
            .Parameters(0).Value = p1
            .Parameters(1).Value = p2
            Debug.Print "Row ", iRow, "p1=" & p1, "P2=" & p2
            .Execute
            count = count + 1
        End If
     Next
  End With

  ' end
  MsgBox "Rows processed = " & count, vbInformation, "Updates Complete"
  con.Close

  Set con = Nothing
End Sub

Ответы [ 2 ]

1 голос
/ 03 марта 2020

Запустите запрос SELECT, чтобы убедиться, что записи, которые вы хотите обновить, существуют

Sub CheckExists()

    Dim con As Object, rs As Object, SQL As String
    Set con = mydbConnect()

    SQL = "SELECT count(*) " & _
          "FROM dbo.cxu_all_load_control " & _
          "WHERE mst_ship_num = ?"

    Set cmd = CreateObject("ADODB.Command")
    With cmd
        .ActiveConnection = con
        .CommandText = SQL
        .CommandType = 1 'adCmdText
        .Parameters.Append .CreateParameter("P2", advarchar, 1, 50) ' adParamInput = 1
    End With

    Dim ws As Worksheet, wbOut As Workbook, iLast As Long
    Set ws = ThisWorkbook.Sheets("Dwell Report")
    iLast = ws.Range("A" & Rows.count).End(xlUp).Row

    Set wbOut = Workbooks.Add ' new workbook for results
    wbOut.Sheets(1).Range("A1:B1") = Array("mst_ship_num", "Count")

    ' scan sheet and update db
    Dim p2 As String, r As Long
    r = 2
    With cmd
        For iRow = 5 To iLast
            p2 = ws.Range("A" & iRow).Value
            If Len(p2) > 0 Then
                .Parameters(0).Value = p2
                Set rs = .Execute(SQL)
                r = r + 1
                wbOut.Sheets(1).Cells(r, 1) = p2
                wbOut.Sheets(1).Cells(r, 2) = rs(0)
            End If
        Next
    End With

    wbOut.Activate
End Sub
0 голосов
/ 03 марта 2020

Попробуйте, как это ... увидеть все комментарии, как вы go ...

Sub UpdateSqlServer()

' Set a reference to:
' Microsoft ActiveX Data Objects 6.1 Library

'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String

'Create a new Connection object
Set cnn = New adodb.Connection

'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=NameOfDatabase;Data Source=NameOfServer"


'Create a new Command object
Set cmd = New adodb.Command

'Open the Connection to the database
cnn.Open

'Associate the command with the connection
cmd.ActiveConnection = cnn

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText

'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2020-01-01' WHERE EMPID = 1"

'Pass the SQL to the Command object
cmd.CommandText = strSQL


'Execute the bit of SQL to update the database
cmd.Execute

'Close the connection again
cnn.Close

'Remove the objects
Set cmd = Nothing
Set cnn = Nothing

End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...