Setting parameter values in SQL for MS Access

时间:2015-04-24 18:37:23

标签: sql ms-access parameters

E.g. I have a SELECT query Q with a text parameter named P. I would like to write something like this:

SET P = 'sometext'; SELECT * FROM Q;

Edit: Since it causes so much confusion, let's say Q is the following query in the Queries collection:

PARAMETERS P text; SELECT SomeField FROM SomeTable WHERE SomeField = P;

(but note that P generally may appear anywhere parameters are allowed, it's just a simple example!)

Is it possible?

Edit2: Ok, I got it, not possible with Jet SQL, credits to @Rahul Tripath; @HansUp. Thanks to everyone who tried.

1 个答案:

答案 0 :(得分:1)

MS Access支持input parameters,如下所示:

<强> [编辑]

如果我理解你的话......

PARAMETERS [cdate] DATE;
SELECT * 
FROM (
    SELECT [UserId], [UserName], [CreationDate]
    FROM MyUsers
    WHERE [CreationDate] = [cdate]
) AS Q;

有关详细信息,请参阅:
Use parameters to ask for input when running a query
Run a parameter query within an Access form

<强> [EDIT2]

最后,我想我明白你的意思了。您想要创建动态查询。 MS Access不直接支持SQL代码中的功能。要实现这一点,您需要使用VBA:

Dim par as String 
Dim sql as String

par = "whatever"
sql = "SELECT .... " & vbcr & _
    "FROM (" & vbcr & _
        "SELECT ..." & vbcr & _
        "FROM ..." & vbcr & _
        "WHERE [FilteredField] = " & par & vbcr & _
    ") AS Q;"
DoCmd.RunSQL sql
'or
'CurrentDb.Execute sql