我有一个SQL数据库,我想更新特定的表和特定的字段。
我将Excel电子表格中的记录插入到我创建的另一个使用dbo模式的数据库中。
我在play数据库中编写了一个带有UPDATE的存储过程,该存储过程更新了erp模式中的表。如果我在SSMS中执行sp,它将起作用。如果我从Excel执行sp,它将失败。
我通过执行SELECT sp,将记录集返回到电子表格,然后为每行创建并执行UPDATE来更新Play数据库表。当然,这需要更长的时间。
这是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