##GlobalTableMain
我目前通过宏打开并用名称填充一个全局表。该表通过以下方式创建:
Public Sub ExecuteSQLQuery(sQuery As String)
Dim cn As New ADODB.Connection
cn.Open strConnection
cn.Execute "SET NOCOUNT ON;" & sQuery
cn.Close
End Sub
查询大致如下所示:
CREATE TABLE ##GlobalTableMain (Columns here);
INSERT INTO ##GlobalTableMain (Columns) VALUES
BUNCH OF ROWS
所有这些工作都很好,直到我尝试添加另一个由于另一个因素而变得必要的宏。
有问题的查询:
Sub AggregateSQLTempTable(sTempTable As String, sAggClm As String)
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset, sQuery As String
Dim selectClms As String, groupClms As String
cn.Open strConnection
sQuery = "SET NOCOUNT ON; SELECT tempdb.sys.columns.name FROM tempdb.sys.columns WHERE tempdb.sys.columns.object_id = Object_Id('tempdb.." & sTempTable & "')"
rs.Open sQuery, cn
sQuery = vbNullString
selectClms = vbNullString
groupClms = vbNullString
If Not (rs.EOF Or rs.BOF) Then
rs.MoveFirst
Do While Not (rs.EOF Or rs.BOF)
selectClms = selectClms & IIf(Len(selectClms) > 0, ", ", "") & IIf(rs!Name = sAggClm, "SUM(" & rs!Name & ") " & rs!Name, rs!Name)
groupClms = groupClms & IIf(rs!Name = sAggClm, "", IIf(Len(groupClms) > 0, ", ", "") & rs!Name)
rs.MoveNext
Loop
sQuery = vbNullString
sQuery = "SELECT * INTO #aggTempTable FROM (SELECT " & selectClms & " FROM " & sTempTable & " GROUP BY " & groupClms & ") a;"
sQuery = sQuery & Chr(10) & "TRUNCATE TABLE " & sTempTable & ";"
sQuery = sQuery & Chr(10) & "INSERT INTO " & sTempTable & " SELECT * FROM #aggTempTable;"
sQuery = sQuery & Chr(10) & "DROP TABLE #aggTempTable;"
cn.Execute sQuery
End If
rs.Close
cn.Close
End Sub
据说SET NOCOUNT ON
应该防止这种情况,但不幸的是它对我不起作用。