访问SQL Server语法转换

时间:2016-07-25 10:11:16

标签: sql-server vb.net sql-server-2008 ms-access database-migration

我最近移动了一个我从Access到MS SQLServer的项目,但这当然意味着我需要更改我的SQL语句中的一些代码。

我有这个子例程,我获取字段DateRenew在30天内的所有记录...如何将其转换为SQL?目前我收到以下错误消息

  

未处理的类型' System.Data.OleDb.OleDbException'发生在MaintenanceControl.exe

中      

其他信息:'#'

附近的语法不正确
    Private Sub btn30Days_Click(sender As Object, e As EventArgs) Handles btn30Days.Click

    Dim td As String
    Dim sd As String
    sd = Format(Today.AddDays(31), "MM/dd/yyyy")
    td = Format(Today, "MM/dd/yyyy")

    Try
        sql = "SELECT * FROM dbo.tblContracts WHERE DateRenew BETWEEN #" & sd & "# AND #" & td & "#;"
        conAd = New OleDb.OleDbDataAdapter(sql, con)
        conset = New DataSet
        conAd.Fill(conset)
        ugModules.DataSource = conset

    Catch ex As Exception
        errorLog(ex.Message, ex.StackTrace)
        MsgBox("Failed to retrieve contract information from database, refer to error log")
    End Try

End Sub

2 个答案:

答案 0 :(得分:0)

更容易且更不容易出错的是直接使用SQL Server的日期函数。

sql = "SELECT * FROM dbo.tblContracts WHERE DateRenew BETWEEN 
       CONVERT(DATE, GETDATE()) AND DATEADD(DAY, 31, CONVERT(DATE, GETDATE()))"

(换行时换行)

如果GETDATE()包含当前时间并不重要,则可以省略CONVERT(DATE, ...)部分。

答案 1 :(得分:-1)

 Dim td As String
Dim sd As String
sd = Format(Today.AddDays(31), "yyyyMMdd")
td = Format(Today, "yyyyMMdd")

Try
    sql = "SELECT * FROM dbo.tblContracts WHERE DateRenew BETWEEN ''" & sd & "'' AND ''" & td & "'';"
    conAd = New OleDb.OleDbDataAdapter(sql, con)
    conset = New DataSet
    conAd.Fill(conset)
    ugModules.DataSource = conset

Catch ex As Exception
    errorLog(ex.Message, ex.StackTrace)
    MsgBox("Failed to retrieve contract information from database, refer to error log")
End Try

YYYYMMDD是SQL(iso)的日期格式 #被SQL中的'(单引号)替换 在VB中你需要输入'as'作为转义序列 - 输入单引号作为TWO consequitve SINGLE引号