我是C#和SQL的初學者,我有這個SQL插入語句,我想執行。它要求我想要插入的其他變量中的表名。必須聲明表變量@table
但是當我運行該控制檯應用程序,我得到這個錯誤:
必須聲明表變量@table
這是代碼的一部分:
StreamReader my_reader = getFile(args);
string CS = formCS();
try
{
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand com = new SqlCommand("insert into @table (time, date, pin) values (@time, @date, @pin)", con);
con.Open();
Console.WriteLine("Enter table name:");
Console.Write(">> ");
string tblname = Console.ReadLine();
com.Parameters.AddWithValue("@table", tblname);
string line = "";
int count = 0;
while ((line = my_reader.ReadLine()) != null)
{
Dictionary<string, string> result = extractData(line);
com.Parameters.AddWithValue("@time", result["regTime"]);
com.Parameters.AddWithValue("@date", result["regDate"]);
com.Parameters.AddWithValue("@pin", result["regPin"]);
count += com.ExecuteNonQuery();
com.Parameters.Clear();
}
Console.WriteLine("Recoreds added : {0}", count.ToString());
Console.WriteLine("Press Enter to exit.");
}
Console.ReadLine();
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
不允許插入statememt的表名作爲變量。查看sp_exec是否需要類似這一點。 – rene