Skip to content
Advertisement

Is there a way to SELECT a database table using a variable?

I tried this statement:

string query = "SELECT question FROM '" + GlobalVariables.dbQCode + "' WHERE [question_code] = '" + GlobalVariables.questionCode + "' ";

and when I run the code it is giving me an exception:

Syntax error in query. Incomplete query clause.

Is there a way where I can use my variable? I want it to work because I want this code to work also:

if (comboBox1.Text == "General Education"){
                GlobalVariables.subjectCode = "GenEd_English";
                GlobalVariables.dbQCode = "Gen_Ed_Question_Items";
                GlobalVariables.dbCCode = "Gen_Ed_Choice_Bank";
                if (comboBox2.Text == "English")
                {
                    GlobalVariables.subjectName = "ENGLISH";
                }
                
}

Advertisement

Answer

Single quotes (') denote string literals. Object names, such as table names, should not be surrounded by quotes:

string query = "SELECT question FROM " + GlobalVariables.dbQCode + " WHERE [question_code] = '" + GlobalVariables.questionCode + "' ";
// Quotes removed here --------------^-----------------------------^
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement