1

Hi I'm trying to get SQL to select from a table which the user has chosen from a list box

Heres my code

activity := cmbActivity.Text; //this is where the user selects a table to choose from
qryStudents.SQL.Text := 'SELECT * FROM :activity WHERE CompNo = :iCompNo'; //error here
qryStudents.Parameters.ParamByName('activity').Value:= activity; 
qryStudents.Parameters.ParamByName('iCompNo').Value := iCompNo;
qryStudents.Open;

I keep getting a syntax error after FROM in the SQL code (:activity) Any help will be appreciated

1 Answer 1

3

You can't define the table part of your select as a parameter, you'll need to dynamically build that part of the select statement.

activity := cmbActivity.Text;
qryStudents.Close;
qryStudents.SQL.Text := 'SELECT * FROM '  + activity + ' WHERE CompNo = :iCompNo';
qryStudents.Parameters.ParamByName('iCompNo').Value := iCompNo;
qryStudents.Open;

:iCompNo OTOH is fine to be defined as a parameter, in order to prevent SQL injection.

Sign up to request clarification or add additional context in comments.

9 Comments

It still gives the same issue with that change
Are you sure that the activity variable had a valid table name ?. By the way, you had a qryStudents.Edit at the start of your code, I have changed it for qryStudents.Close, because your query should be closed when you change its SQL property.
Yes it is a valid table name. I did close the qryStudents.Edit before I worked on this snippet. I get a syntax error on exactly how it is in the title which breaks my program
@JaynillGopal: Marc is right that you cannot specify the table you are querying using a parameter, so +1 for that. Which Sql back-end and Delphi query component are you using.
I'm using an ADOQuery component in delphi with a Provider=Microsoft.Jet.OLEDB.4.0 connection
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.