解决'IN'条款限制问题

时间:2015-11-09 21:20:48

标签: sql-server excel vba

我正在尝试编写一个宏来使用IN子句从我们的数据库进行查询,除了一个问题。我达到了SQL Server的IN子句的限制。

我的宏看起来像这样:

Dim row_count As Double
row_count = ActiveSheet.UsedRange.Rows.Count - 1
half_row_count = row_count
Dim i As Double
Dim products As String
For i = 2 To half_row_count
    Dim product_id As String
    product_id = Cells(i, 1).Value
    'test = sixtyDays(product_id, conn)
    'Cells(i, 10).Value = test
    products = products & "'" & product_id & "'" & ", "
Next i
Dim sample As New ADODB.Recordset
products = Left(products, Len(products) - 2)
Set sample = sixtyDays(products, conn)
Sheets(1).Range("K2").CopyFromRecordset sample
conn.Close

Function sixtyDays(ProductID As String, new_conn As ADODB.Connection) As ADODB.Recordset
    Dim sConnString As String
    Dim rst As New ADODB.Recordset
    Dim recordsAffecfted As Long
    StrQuery = "SELECT ProductAnalysisByMonth.SalesQty FROM ProductAnalysisByMonth WHERE ProductAnalysisByMonth.ProductID IN (" + ProductID + ") AND ProductAnalysisByMonth.Month = " + CStr(Month(Date) - 2)
    rst.Open StrQuery, new_conn
    Set sixtyDays = rst
End Function

所以我需要一些如何将查询拆分成更小的块,除了传递给SQL查询的参数数量每周都不同。

处理此问题的最有效方法是什么?

1 个答案:

答案 0 :(得分:2)

创建一个表函数,它将您的字符串结果返回到一个数据集,该数据集可以插入CTE,临时表或直接用于连接。这是解决这个限制的最有效方法。以下是Ole Michelsen网站的链接,该网站提供了一个简单但灵活的解决方案。

链接:http://ole.michelsen.dk/blog/split-string-to-table-using-transact-sql.html