在动态SQL字符串生成器中封装字段的问题

时间:2018-07-17 05:55:33

标签: sql vba vb.net

我正在尝试为我的应用程序创建一个动态SQL字符串生成器,并且在用括号括起来的字段名称时遇到一些问题。

我的代码如下:

mp.clear();

当我在FieldsArray中的多个字段中运行此代码时,我会不断获得以下输出,并带有不必要的前导空格。

Public Sub BuildDynamicSQL( _
                         FieldsArray() As String, _
                         ByVal TableName As String)                            

    ' Declarations ->
    Dim strSQL As String: strSQL = vbNullString
    Dim Field As Variant
    Dim i As Integer: i = 0

    ' Validate fields array ->
    If IsEmpty(FieldsArray) Then Exit Sub

    ' Construct SQL using Fields array ->
    strSQL = "SELECT "
    For Each Field In FieldsArray
        If i = 0 Then
            strSQL = strSQL + "[" + Field + "]"
        Else
            strSQL = strSQL + "," + "[" + Field + "]"
        End If
        i = i + 1
    Next

    strSQL = strSQL + " FROM " + TableName

End Sub

有人知道如何使它按预期工作吗?

非常感谢。

1 个答案:

答案 0 :(得分:1)

这是一个接受paramarray参数并返回字符串的函数的通用示例。

Option Explicit

Sub main()
    Dim sql As String

    sql = buildMySql("mytable")
    Debug.Print sql

    sql = buildMySql("mytable", "fld1", "fld2", "fld3", "fld4")
    Debug.Print sql
End Sub

Function buildMySql(tbl As String, ParamArray flds()) As String
    Dim str As String, f As Long

    If IsMissing(flds) Then
        str = "select * from [" & tbl & "];"
    Else
        str = "select "
        For f = LBound(flds) To UBound(flds)
            str = str & "[" & flds(f) & "]" & IIf(f < UBound(flds), Chr(44), vbNullString)
        Next f
        str = str & " from [" & tbl & "];"
    End If

    buildMySql = str
End Function

'results
select * from [mytable];
select [fld1],[fld2],[fld3],[fld4] from [mytable];