简体   繁体   中英

MS Access using VBA and Form, build a query string and run it

I have a MS Access form where it will ask users to select or type in words that will be used in the where clause for the query.

When the button is clicked, it will build the string and use that to run the query. This will be a read only and to view the subset results from a link table in SQL Server. Nothing more. I tried it with DoCmd.RunSQL but that is only for action type like update, delete, etc.

On click button event, it will have similar query.

strSQL = "Select top 10 * Where ID = ''" + textbox1.value + "'' from linked_Table_Name;"

This did not work.

DoCmd.RunSQL strSQL

Firstly, and most importantly, never concatenate user-obtained data as part of a SQL statement . Any application which uses this technique is wide open to a SQL injection attack and will also fail if the user includes a string delimiter (such as a single quote) or other reserved character in the input they provide.

Instead, use parameters.

For your scenario, I might suggest creating a saved query with the SQL:

select top 10 t.*
from linked_Table_Name t
where t.ID = Forms![Your Form Name]![textbox1]

Where Your Form Name is the name of your form containing the control textbox1 .

Then, your on-click event can simply call the OpenQuery method of the DoCmd object:

DoCmd.OpenQuery "YourSavedQuery"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM