Search code examples
sqlparameterized-query

Parameterized SQL in FROM clause


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


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.