locked
Use Table Name as a parameter ( For Dynamic table name) RRS feed

  • Question

  • hi to everyone i'm trying to send a table name as a argument but i'm getting an error  let me how to fix it

    my code is...

    public DataSet showQuestionAll(string tblName)
        {
            string qry = "Select QName from @tblname";
            SqlCommand cmd = new SqlCommand(qry, conn);
            cmd.Parameters.AddWithValue("@tblname", tblName);
            SqlDataAdapter dt = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dt.Fill(ds);
            return ds;

        }


    Tuesday, September 15, 2015 12:52 PM

Answers

All replies

  • You cannot pass a table name as an argument. This is not supported. You will have to concatenate the string:

    string qry = "Select QName from " + tableName;


    But this shouldn't be a problem  as there can only be a fixed set of possible correct values for the table name anyway as Jon Skeet suggests here: http://stackoverflow.com/questions/17947736/sqlparameter-does-not-allows-table-name-other-options-without-sql-injection-at

    Please refer to the link above for more information.

     
    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

    Tuesday, September 15, 2015 1:01 PM
  • Check if the next query works in your environment:

    string qry = "DECLARE @q AS nvarchar(MAX) = 'SELECT QName FROM ' + QUOTENAME(@tblname); EXEC (@q)";


    • Edited by Viorel_MVP Tuesday, September 15, 2015 6:46 PM
    Tuesday, September 15, 2015 6:46 PM