在哪里使用布尔函数(SQL)?

时间:2015-01-06 14:38:50

标签: sql vba

我正在尝试使用一个函数,该函数在SQL语句的某个位置后生成一个布尔值。

该函数的作用是验证所选日期是否在两个const日期之内并产生一个布尔值。我遇到了SQL语法问题

Sqlstring = "Select count() from [Orders].[Date]" & _ 
where " & Function([Orders].[Date]) = True & "" 

我不确定sql语句是否正确。

编辑这里是代码:

public StartDate as String
public EndDate As string

Private Function GetOrdersNumbers() As Integer
Dim rsData As ADODB.RecordSet

Dim szConnect As String
Dim szSQL As String
Dim DataSource As String

DataSource = "C:\Users\user\Desktop\db.mdb"
szConnect = "Provider=Microsoft.Jet.OLEBD.4.0;" & _
"Data Source=" & DataSource & ";" & _
"user ID=admin;password=;"

szSQL = "SELECT COUNT(*) FROM [Et_Journal Livraison Fournisseur] WHERE [Et_Journal Livraison Fournisseur].[Date] BETWEEN [@StartDate] And [@EndDate] "
Set rsData = New ADODB.RecordSet

rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText
If Not rsData.EOF Then
Range("A01").CopyFromRecordset RecordSet
GetOrdersNumbers = CInt(Range("A01").Value)
End If
End Function

1 个答案:

答案 0 :(得分:1)

您没有提供有关数据库引擎的信息......不过

我建议使用这样的查询:

SELECT COUNT(*)
FROM Orders
WHERE [Date] BETWEEN [@date1] AND [@date2]

其中
@ date1 @ date1 是参数

没有理由使用功能。

<强> [编辑]

感谢您的澄清。看看下面的代码:

Option Explicit


Sub Test()
Dim d1 As Date
Dim d2 As Date

d2 = DateSerial(2015, 1, 6)
d1 = DateAdd("MM", -3, d2)

MsgBox GetOrdersNumbers(d1, d2)

End Sub

Function GetOrdersNumbers(ByVal StartDate As Date, ByVal EndDate As Date) As Long
Dim oConn As ADODB.Connection, oRst As ADODB.Recordset
Dim sConnString As String, sQry As String
Dim retVal As Long

sConnString = "Provider=Microsoft.Jet.OLEBD.4.0;" & _
            "Data Source=C:\Users\user\Desktop\db.mdb;" & _
            "user ID=admin;password=;"

Set oConn = New ADODB.Connection
With oConn
    .ConnectionString = sConnString
    .Open
End With

sQry = "SELECT [Date] As MyDate" & vbCr & _
        "FROM [Et_Journal Livraison Fournisseur]" & vbCr & _
        "WHERE [Et_Journal Livraison Fournisseur].[Date] BETWEEN #" & StartDate & "# And #" & EndDate & "#"

Set rsData = New ADODB.Recordset

oRst.Open szSQL, oConn, adOpenStatic, adLockReadOnly

retVal = oRst.RecordCount

End If

Exit_GetOrdersNumbers:
    On Error Resume Next
    oRst.Close
    Set oRst = Nothing
    oConn.Close
    Set oConn = Nothing
    GetOrdersNumbers = retVal
    Exit Function

Err_GetOrdersNumbers:
    MsgBox Err.Description, vbExclamation, Err.Number
    Resume Exit_GetOrdersNumbers
End Function