Link to home
Start Free TrialLog in
Avatar of huangs3
huangs3Flag for Canada

asked on

SQL Server 2005 programming with Visual Studio 2005 C#: how to declare table variable used by C#?

Hi Experts:

    I used the following code as an attempt to parametermize a table name of a SQL Server 2005 database.
    However, I got the error message in attached picture. I was asked for a "table variable", but I don't know how to declare it. Can you help me to make the code work without using Ac-Hoc method such as string concatenation and hard-coding?
    Thank you very much!

Sui
System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection(ConnectionString);
Connection.Open();
System.Data.SqlClient.SqlCommand Command = Connection.CreateCommand();
Command.CommandType = CommandType.Text;
Command.CommandText = "UPDATE @TableName SET Name = @Name, WHERE Id = @Id";
Command.Parameters.Add("Id", SqlDbType.Int);
Command.Parameters.Add("Name", SqlDbType.VarChar);
Command.Parameters.Add("TableName", SqlDbType.VarChar);
Command.Parameters["TableName"].Value = "Building";
Command.Parameters["Id"].Value = 1;
Command.Parameters["Name"].Value = "Inventory1";
 Command.ExecuteNonQuery();

Open in new window

TableVarErr.jpg
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

SQL parameters need @ as the first character of the name. See code snippet.
System.Data.SqlClient.SqlConnection Connection = new  System.Data.SqlClient.SqlConnection(ConnectionString);
Connection.Open();
System.Data.SqlClient.SqlCommand Command = Connection.CreateCommand();
Command.CommandType = CommandType.Text;
Command.CommandText = "UPDATE @TableName SET Name = @Name, WHERE Id = @Id";
Command.Parameters.Add("@Id", SqlDbType.Int);
Command.Parameters.Add("@Name", SqlDbType.VarChar);
Command.Parameters.Add("@TableName", SqlDbType.VarChar);
Command.Parameters["@TableName"].Value = "Building";
Command.Parameters["@Id"].Value = 1;
Command.Parameters["@Name"].Value = "Inventory1";
Command.ExecuteNonQuery();

Open in new window

Avatar of huangs3

ASKER

Hi FernadoSoto:

    No, it should not need @ character in Parameters.Add and Parameters["TableName"] expression. If I hard-code the table name but leave other parameters, the code would work. I tried you last idea and got "Must declare the table variable "@TableName"" error message.
    Any further idea?
    Thank you!
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of huangs3

ASKER

Hi FernandoSoto:

    Thank you for your follow up. That means no smarter solution than string concatenation for this case. I will accept your answer.