ORA-01036 - illegal variable name/number

I have a dynamic SQL for searching records in Oracle, and VS2017 code analysis reports warning about using parameterized SQL query for this line (1st line, this code works):

string SQL = "SELECT " + string.Join(",", my_columns.ToArray()) + " FROM MyTable ";
string where_condition = " WHERE ";

//the rest of code follows as this...
if (!string.IsNullOrEmpty(textbox1.Text))
  SQL = string.Concat(SQL, where_condition, " Name like :name");
  cmd.Parameters.Add(new OracleParameter("name", string.Concat("%", textbox1.Text, "%")));
  where_condition = " AND ";
} //...

So, I tried to put column names as parameters because of warning, but then I get ORA-01036- illegal variable name/number error:

 string SQL = "SELECT :columns FROM MyTable ";
 cmd.Parameters.Add(new OracleParameter("columns", string.Join(",", 
 string where_condition = " WHERE ";

What is wrong, maybe column names cannot be passed as parameters ? Or is there any other way to avoid warning in VS code analysis ?

1 answer

  • answered 2018-05-16 06:48 Daisy Shipton

    You're right - column names can't be passed as parameters. That part has to be done dynamically, unless you want to change your database structure very significantly. (You could have one column with a value which is the logical column name, and one column for the value. I'm not recommending this - it's very much not how databases are intended to be used.)

    The warning you're getting is there to avoid SQL injection attacks. When building the query dynamically, you have to do that differently. You basically need to make sure you have a whitelist of column names, and only build up SQL including those names.

    You may well still get a code analysis warning at that point, but you should disable that just for this piece of code, with a comment explaining that you understand the warning, and what you've done to remove the risk of SQL injection attacks.