Question

Using OleDbCommand. I can add SQL parameters and thus keep the query safe from SQL-injection, but is there a way to do this within the FROM cluase.See below

THIS WORKS

query = "Select * From Company Where @param = 1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);

DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;

//Add Parameters
Command.Parameters.AddWithValue("param", "ID");
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];

it returns a nice table with the wonderful row where id = 1

BUT

I am looking for something like this, note the FROM CLAUSE

query = "Select * From @tableName Where @param = 1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);

DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;

//Add Parameters
Command.Parameters.AddWithValue("param", "ID");
Command.Parameters.AddWithValue("tableName", "Company");
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];

The DBMS keeps returning with "Error in From clause"

PS everything is spelled correctly - I triple checked


To All - Thanks but Alas i shall stick to just Parameterized SQL. I don't like Dynamic SQL One BIT

Was it helpful?

Solution

You'd have to execute a dynamically concatenated SQL string, which unfortunately would compromise whatever benefits parametrized SQL had afforded you to begin with. See this post.

DECLARE @SQL varchar(250)
SELECT @SQL = 'Select * From ' + @TableName + ' Where ' + @param + ' = 1'
Exec(@SQL)

Not advisable, if you can predetermine the table name through some other means instead.

OTHER TIPS

SQL doesn't support the FROM clause to be parameterized. You can't do it the way you are trying. Probably you can do like this:

query = "Select * From" + tableName + "Where @param = 1";

You cannot use paramaterised object names. You would have to do somthing like

string.format("SELECT * FROM [{0}] WHERE [{1}] = 1", tableName, columnName);

DO SO AT YOUR OWN PERIL

It could be worth checking for square brackets in the input, this is the only way I can currently think off to "Inject" the above example. I am no hacker though and not versed in sql injection. Something like this might work:

        if (tableName.Contains("]"))
        {
            throw new ArgumentException();
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top