【问题标题】:VBA variable in SQL date querySQL日期查询中的VBA变量
【发布时间】:2015-08-07 17:27:03
【问题描述】:

我正在尝试在 SQL 数据库中查询日期在用户输入给定日期之后的所有行。当我用“#”包围我的日期时,我遇到了从“附近语法不正确”到“将表达式转换为算术溢出错误”的各种错误。我当前的代码如下所示:

inputdate = InputBox("Please enter the starting date (mm/dd/yyyy)")
Debug.Print inputdate

querydate = "(DTG > " & Format(inputdate, "MMDDYYYY") & ")"

select StationID, DTG, CeilingFeet from SurfaceOb where " & querydate & " and StationID = 'NZWD'"

DTG 是 SQL 数据库中日期时间组的列名。知道我哪里出错了吗?在过去的几天里,我已经尝试了所有能找到的解决方案,但都没有运气。提前谢谢你。

【问题讨论】:

    标签: sql vba date variables


    【解决方案1】:

    主要问题是日期必须用单引号括起来。这是一个完整的工作示例(减去有效的连接字符串),应该解释如何实现您的目标。请注意,您还需要切换到 ISO 日期格式,其中的顺序是年-月-日 (YYYY-MM-DD)。

    Sub UpdateRecords()
        Dim connection As New ADODB.connection
        Dim recordset As New ADODB.recordset
        Dim connectionString As String
        Dim query As String
        Dim inputdate As Date
        Dim querydate As String
    
        inputdate = InputBox("Please enter the starting date (mm/dd/yyyy)")
        querydate = "(DTG > '" & Format(inputdate, "yyyy-mm-dd") & "')"
        query = "select StationID, DTG, CeilingFeet from SurfaceOb where " & querydate & " and StationID = 'NZWD'"
    
        connectionString = "..."        
        connection.Open connectionString
        recordset.Open query, connection
        ActiveSheet.Range("A1").CopyFromRecordset recordset
    End Sub
    

    【讨论】:

    • 这条查询行最终对我有用 querydate = "(DTG > '" & Format(inputdate, "YYYY-MM-DD") & "')" 谢谢!
    【解决方案2】:

    SQL Server 的日期应格式化为日期或日期/时间,用单引号限定:

    日期采用 ISO 未分隔日期格式

    querydate = "(DTG > '" & Format(inputdate, "yyyymmdd") & "')"
    

    日期/时间采用 ISO 8601 格式

    querydate = "(DTG > '" & Format(inputdate, "yyyy-mm-ddThh:mm:ss.000") & "')"
    

    【讨论】:

      【解决方案3】:

      MySQL 的日期格式为 YYYY-MM-DD。 此外,由于 DTG 是日期时间,因此您需要 DATE(DTG) > DATE(NOW()) 例如 - DATE() 是一个 MySQL 函数,它仅检查日期时间戳的日期部分。

      您的查询应如下所示:

      querydate = "(DATE(DTG) > " & Format(userinput, "YYYY-MM-DD") & ")"
      
      select StationID, DTG, CeilingFeet from SurfaceOb where " & querydate & " and StationID = 'NZWD'"
      

      【讨论】:

        猜你喜欢
        • 2014-09-23
        • 1970-01-01
        • 2020-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多