Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i select from table where tablename is specified as SqlParameter?

I am trying to perform dynamic sql select where I am selecting from a table using a parameter.

SELECT null FROM @TableName 

However I am getting error must declare table variable @TableName. I suspect this is because I am selecting from a table using a variable. I have not needed to do this before.

List<SqlParameter> sqlParams = new List<SqlParameter>()
{ 
    new SqlParameter("TableName", "testtable"),
    new SqlParameter("FieldName", "testfield"),
    new SqlParameter("Find", "testfind"),
};
string sqlSelect = "SELECT null FROM @TableName 
                    WHERE @FieldName LIKE '%' + @Find + '%' ";

DataTable dtSelect = SqlHelper.ExecuteDataset(sqlConn, CommandType.Text, 
                        sqlSelect, 30, sqlParams.ToArray()).Tables[0]; 
//30 = timeout

How can I perform the above using dynamic sql? (no stored procedures please)

like image 474
Valamas Avatar asked Dec 12 '25 16:12

Valamas


1 Answers

You cannot use parameters for things like table and column names. For those you could have a whitelist of possible values and then use string concatenation when building the SQL query.

like image 83
Darin Dimitrov Avatar answered Dec 14 '25 07:12

Darin Dimitrov