在Microsoft SQL查询中仅选择特定数据类型

时间:2017-06-17 10:21:36

标签: vba ms-access select sqldatatypes

在Access 2007中,我需要选择表格中的所有短文本字段。

VBA代码应如下所示:

    Dim strClient As String
    Set dbs = CurrentDb()
    Debug.Print Me.ID

    strClient = "Select * from ANG_CLIENTS where DATA_TYPE='TEXT' AND ID=" & Me.ID

    Set rs = dbs.OpenRecordset(strClient)

我得到"运行时错误3061.参数太少。预计1"在最后一次任务中。

1 个答案:

答案 0 :(得分:1)

您需要定义一个自定义函数来遍历记录集字段并仅提取文本字段的名称。

然后可以将名称添加到SQL脚本中。

Public Function TextDataFileds(rs As DAO.Recordset) As String

    Dim fld As DAO.Field, item As String

    For Each fld In rs.Fields
        If fld.Type = 10 Then 'dbText
            item = IIf(Len(item) = 0, fld.Name, item & ", " & fld.Name)
        End If
    Next fld

    TextDataFileds = item
End Function

然后你可以这样称呼它:

Sub Test()
    On Error GoTo ErrProc

    Dim rs As DAO.Recordset
    Set rs = CurrentDb().OpenRecordset("SELECT TOP 1 * FROM ANG_CLIENTS;")

    Dim sql_ As String
    sql_ = "SELECT " & TextDataFileds(rs) & " FROM ANG_CLIENTS WHERE ID=" & Me!ID

    rs.Close
    Set rs = Nothing

    Set rs = CurrentDb().OpenRecordset(sql_)

    '....

Leave:
    rs.Close
    Set rs = Nothing
    On Error GoTo 0
    Exit Sub

ErrProc:
    MsgBox Err.Description, vbCritical
    Resume Leave
End Sub