2

I'm working on a C# DB project and I keep getting this error when I try to add parameters to the command text.

'Invalid object name '@table'.'

This error appears for every parameter I add.

sqlcmd.CommandText = "INSERT INTO [@table](@iVar, @uVar, @pVar) VALUES (@vali, @val1, @val2)";

sqlcmd.Parameters.AddWithValue("@table", "Data");
sqlcmd.Parameters.AddWithValue("@iVar", "Var1");
sqlcmd.Parameters.AddWithValue("@uVar", "Var2");
sqlcmd.Parameters.AddWithValue("@pVar", "Var3");
sqlcmd.Parameters.AddWithValue("@vali", "Val1");
sqlcmd.Parameters.AddWithValue("@val1", "Val2");
sqlcmd.Parameters.AddWithValue("@val2", "Val3");

sqlcmd.ExecuteNonQuery();
1
  • 1
    You can not pass the table name as parameter to query. Parameters are used for passing values to the command not the table name or column names. Commented Aug 31, 2019 at 3:46

2 Answers 2

1

Table names & column names cannot be passed as a parameter to SQL command. You can, however, use the below.

var tableName = "Data";
var iVar = "Var1";
var uVar = "Var2";
var pVar = "Var3";
sqlcmd.CommandText = $"INSERT INTO [{tableName}]({iVar}, {uVar}, {pVar}) VALUES (@vali, @val1, @val2)";

sqlcmd.Parameters.AddWithValue("@vali", "Val1");
sqlcmd.Parameters.AddWithValue("@val1", "Val2");
sqlcmd.Parameters.AddWithValue("@val2", "Val3");

sqlcmd.ExecuteNonQuery();

Note that $ is used for string interpolation

You will then have to ensure that tableName, iVar, uVar and pVar is whitelisted to avoid any kind of SQL injection attacks if you are taking this value from end-user.

Sign up to request clarification or add additional context in comments.

Comments

0

Tables names need to be static. If you are getting the table name from some form of user input you need to validate it. You can do something like the following using a stored procedure:

DECLARE @sqlCommand varchar(1000)
SET @sqlCommand = 'SELECT * from tablename'
EXEC (@sqlCommand)

or something like

SELECT @sSQL = N'SELECT * FROM' + QUOTENAME(@TableName);
EXEC sp_executesql @sSQL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.