0

I am making an windows application in which I have multiple controls that displays the value from different sql database tables. I want to make an update function that takes table name, columnName as a parameter but its not working.

here is the code

    void updateThis(string tableName, string columnName, string textBoxValue)
    {
        using (SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=FIR_db; User Id = sa; Password = 9889922527"))
        {
            //try
            {
                cmd = new SqlCommand("update @t set @a = @b where profile_id= @c", conn);
                conn.Open();
                cmd.Parameters.AddWithValue("@t", tableName);
                cmd.Parameters.AddWithValue("@a", columnName);
                cmd.Parameters.AddWithValue("@b", textBoxValue);
                cmd.Parameters.AddWithValue("@c", lblprofil.Text);
                cmd.ExecuteNonQuery();
            }
            //catch (SqlException exc)
            //{
            //    DialogResult dr = MessageBox.Show("Error in server. Could not load Designation.", "Error in server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }
    }

when I use this function it shows an sqlException "Must declare the table variable "@t". " By the way is this possible or not.

Vivek Singh
  • 646
  • 3
  • 10
  • 25
  • For update table name use alter table query and try this http://stackoverflow.com/questions/886786/how-do-i-rename-the-table-name-using-sql-query – Pradnya Bolli Apr 20 '15 at 05:22
  • @PradnyaBolli Update table and Alter table are 2 very different things. – Zohar Peled Apr 20 '15 at 05:23
  • I don't think what you are asking is possible, and even if it was I don't think it's a smart thing to do. It seems like you update each parameter individually instead of updating all of the changes in one stored procedure. – Zohar Peled Apr 20 '15 at 05:25
  • 3
    duplicated with http://stackoverflow.com/questions/14003241/must-declare-the-table-variable-table – feiyun0112 Apr 20 '15 at 05:26
  • @feiyun0112 thanks for the link I found my solution – Vivek Singh Apr 20 '15 at 05:35
  • @AdamSmith Note this this solution is still **extremely vulnerable** to sql injection. – Zohar Peled Apr 20 '15 at 05:45
  • At least you have to validate the table name, e.g. no space or special characters -- ; , – Eric Apr 20 '15 at 06:00

0 Answers0