У меня есть база данных SQL, и я хочу обновить определенную таблицу и определенные поля.
Я вставляю записи из электронной таблицы Excel в другую созданную мной базу данных, использующую схему dbo.
Я написал хранимую процедуру с UPDATE в моей базе данных воспроизведения, которая обновляет таблицу в схеме erp.Если я выполняю SP в SSMS, это работает.Если я выполняю sp из Excel, это не удается.
Я обновляю таблицу базы данных Play, выполняя SELECT sp, возвращая набор записей в электронную таблицу, а затем создавая и выполняя UPDATE для каждой строки.Конечно, это займет больше времени.
Вот код для хранимой процедуры ОБНОВЛЕНИЕ.В целях тестирования моя процедура теперь возвращает следующую строку из SQL
SELECT @Rows AS i_Rows, DATEDIFF(MS,@Start, @End) / 1000 AS i_Seconds, (DATEDIFF(MS,@Start, @End) - (DATEDIFF(MS,@Start, @End)/1000)) AS i_Miliseconds
Sub ExecuteProc()
Dim o_Connection As ADODB.Connection, o_Recordset As ADODB.Recordset
Dim o_Command As ADODB.Command
Dim s_ConnString As String, s_StoredProcName As String, s_ProjectID, s_Name, s_SQL1 As String
Dim b_ProjHours, b_JobHours, b_Dates As Boolean
Dim ws As Worksheet
Dim l_row, l_count As Long
Dim t_Start, t_End As Date
Dim i_Seconds As Integer
' Determine the values of certain variables
With ActiveSheet
s_Name = .Name
b_JobHours = .chkHours.Value
b_Dates = .chkDates.Value
s_ProjectID = .Cells(15, "B").Value
End With
DataWS
' Make UpdateJobOper the selected sheet
With Worksheets("DATA")
.Select
.Cells.ClearContents
End With
' Create new Connection, Recordset, Command, and Connection String
Set o_Connection = New ADODB.Connection
Set o_Recordset = New ADODB.Recordset
Set o_Command = New ADODB.Command
s_ConnString = "Driver={SQL Server};SERVER=SQLSERVER;DATABASE=Play;UID=BIExcel;PWD=BIExcel;WSID=;"
On Error GoTo CloseConnection
' Open the Connection using the connection string
o_Connection.Open s_ConnString
' Stored Procedure Name and Project ID parameter
s_StoredProcName = "Play.dbo.BIspUpateJobOper"
' Define the command used to open the stored procedure
With o_Command
.ActiveConnection = o_Connection
.CommandType = adCmdStoredProc
.CommandText = s_StoredProcName
.Parameters.Append .CreateParameter("@ProjectID", adVarChar, adParamInput, 25, s_ProjectID)
End With
' Return the recordset using the command and paste it into the DATA worksheet starting at cell A2
Set o_Recordset = o_Command.Execute
Sheets("DATA").Range("A1").CopyFromRecordset o_Recordset
' Close the recordset and connection to the SQL Server
o_Recordset.Close
o_Connection.Close
On Error GoTo 0
On Error GoTo 0
DeleteDataWS
Exit Sub
CloseConnection:
Application.ScreenUpdating = True
DeleteDataWS
MsgBox "Failed to open SQL Connection", vbCritical, "SQL Error"
o_Connection.Close
End Sub
Public Function last_row_with_data(ByVal lng_column_number As Long, shCurrent As Variant) As Long
last_row_with_data = shCurrent.Cells(Rows.Count, lng_column_number).End(xlUp).Row
End Function
Sub DataWS()
' Add a new worksheet called DATA
' If the worksheet already exists, clear it
On Error GoTo AddSheet
With Sheets("DATA")
.Select
.Cells.ClearContents
End With
Exit Sub
' If it does not exist add it
AddSheet:
ActiveWorkbook.Sheets.Add.Name = "DATA"
End Sub
Sub DeleteDataWS()
On Error GoTo GetOutOfHere
Application.DisplayAlerts = False
Worksheets("DATA").Delete
Application.DisplayAlerts = True
GetOutOfHere:
End Sub