2012-06-21 59 views
2

我不知道這是否可能在MS Access中,但我想要做的是檢測破折號( - )並在SQL語句和/或逗號中使用Between。如何使用破折號( - )作爲標準的值

Ex。我有一個名爲「Books」的表格,其中包含字段:BookID,Title,Subject。

現在我怎麼可以查詢書籍表,允許用戶輸入一個值,像一個文本框:

1 or 1-5 or 1,3,4. 

如果該值爲1的SQL語句應該是:

SELECT * FROM Books WHERE BookID = 1 

如果那麼sql語句的值應該是:

SELECT * FROM Books WHERE BookID BETWEEN 1 And 5 

如果值爲1,3,4那麼sql語句應該是:

SELECT * FROM Books WHERE BookID IN (1,3,4) 

回答

3

從東西我已經有切割;

s = "SELECT * FROM Books WHERE BookID" & parseSarg("11,22,33") 

使用;

Public Function parseSarg(str As String) As String 
    Dim re As Object: Set re = CreateObject("vbscript.regexp") 
    re.Global = True 
    Select Case True 
     '//is number 
     Case reTest(re, "^\d+$", str):   parseSarg = " = " & str 
     '//is number-number 
     Case reTest(re, "^\d+-\d+$", str):  parseSarg = " BETWEEN " & Replace$(str, "-", " AND ") 
     '//is number,number[,number] 
     Case reTest(re, "^\d+(?:,\d+)*$", str): parseSarg = " IN (" & str & ")" 
     '//is >number 
     Case reTest(re, "^>\s*\d+$", str):  parseSarg = " >" & Mid$(str, 2) 
     Case Else 
      parseSarg = " = 0 AND 1=0" 
    End Select 
End Function 

Function reTest(re As Object, pattern As String, value As String) As Boolean 
    re.pattern = pattern 
    reTest = re.Test(value) 
End Function 
+0

它來自訪問中的文本框,所以VBA鉤應該沒問題 –

0
SELECT Books.Title FROM Books WHERE Books.BookID > 1 AND Books.BookID < 5; 
+0

嗨,值必須來自一個文本框。只有一個文本框。 – jaypabs