【发布时间】:2020-06-18 11:05:33
【问题描述】:
这个问题来自here。我现在需要做的是在 SQL 中将 insert into 命令分解,这样我就不会超出限制。
这是我目前所拥有的:
Sub second_export()
Dim sSQL As String, sCnn As String, sServer As String
Dim db As Object, rs As Object
sServer = "CATHCART"
sCnn = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Portfolio_Analytics;Data Source=" & sServer & ";" & _
"Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;"
Set db = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
If db.State = 0 Then db.Open sCnn
Dim rw As Range, n As Long
Dim GLID, category, dt, amount
PropertyName = ActiveSheet.Range("F2").Value
InsertedDate = ActiveSheet.Range("G2").Value
StrSQL = "INSERT INTO SBC_Performance_Metrics VALUES"
Values = ""
For Each rw In ActiveSheet.Range("H2:AS47").Rows
'fixed per-row
GLID = Trim(rw.Cells(1).Value)
category = Trim(rw.Cells(2).Value)
'loopover the date columns
For n = 3 To rw.Cells.Count
dt = rw.Cells(n).EntireColumn.Cells(1).Value 'date from Row 1
amount = rw.Cells(n).Value
'Debug.Print PropertyName, GLID, category, amount, dt
Values = Values & "('" & GLID & "', " & "'" & PropertyName & "', " & "'" & category & "', " & amount & ", " & "'" & dt & "', " & "'" & InsertedDate & "'),"
'Debug.Print Values
Next n
Next rw
StrSQL = StrSQL & Values
StrSQL = Left(StrSQL, Len(StrSQL) - 2)
StrSQL = StrSQL & ");"
Debug.Print StrSQL
'Set rs = db.Execute(StrSQL)
End Sub
一切都符合我的预期,但我需要以某种方式分解 INSERT INTO 部分,以免超过 1000 次插入限制。
非常感谢任何建议。
【问题讨论】:
-
如果您跟踪当前拥有的数量,您可以在达到该数量时在循环中执行插入,重置计数器并重置查询字符串。然后(如果您有确切的插入块的倍数)在循环之后仅在该数字大于 0 时执行插入。您也可以考虑不按插入的记录数,而是当您的
Values字符串超过一定长度(如果长度不为0,则仅在循环后插入)。 -
@Uueerdo 我是 VBA 的新手,但我正在尝试插入大约 1600 多行。如果您知道如何修改我的代码,请提供答案。
-
我的 VBA真的生锈了,所以我应该做的最好的描述是高级别的。
-
我会改用类似这样的不同方法:stackoverflow.com/questions/44958471/… 这样会更容易管理。
-
因为没有人抱怨不使用parameters,我这样做并阅读bobby tables!
标签: sql sql-server excel vba insert