使用Excel列数据创建查询数据库的sql语句

时间:2016-04-07 09:37:38

标签: mysql excel vba

我正在寻找有关如何在excel中读取包含500个user_id的单个列并查询数据库以在WPF应用程序中显示结果的任何建议。用户可以拥有或租用,以便SQL看起来像;

SELECT * FROM users WHERE own= 'user_id' or rent= 'user_id'

对于一个用户来说这很好但我想读取每个user_id并将其连接到SQL语句以从数据库中提取所有结果。任何人都有这么简单的方法吗?

1 个答案:

答案 0 :(得分:1)

根据需要更换范围,归功于加入时的brettdj - Simple VBA array join not working

Sub test()

    Dim strQuery As String
    Dim strVals As String

    Dim rngTarget As Range
    Set rntTarget = Range("A1:A7")

    Dim varArr
    Dim lngRow As Long
    Dim myArray()
    varArr = rntTarget.Value2

    ReDim myArray(1 To UBound(varArr, 1))

    For lngRow = 1 To UBound(varArr, 1)
        myArray(lngRow) = varArr(lngRow, 1)
    Next

    strVals = "('" & Join$(myArray, "','") & "') "

    strQuery = "SELECT * FROM users WHERE own in " _
        & strVals & "or rent in " & strVals


End Sub