【问题标题】:Select only certain data type in Microsoft SQL query在 Microsoft SQL 查询中仅选择某些数据类型
【发布时间】:2017-11-20 01:36:54
【问题描述】:

在 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”。

【问题讨论】:

    标签: vba ms-access select sqldatatypes


    【解决方案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
    

    【讨论】:

    • @Parfait 谢谢,我忽略了这一点。
    • @Parfait:“IIf 不是 VBA 函数”......哦,是的。输入VBA.I,IntelliSense 会将其作为您的首选。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2019-10-25
    • 2021-04-05
    相关资源
    最近更新 更多