有以下一段代碼:
SqlConnection conn = DBC.DatabaseConnection();
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from @tableName";
cmd.Parameters.Add("@tableName", SqlDbType.NVarChar, 30).Value = DropDownList1.SelectedValue;
SqlDataReader sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
conn.Close();
為什麼運行時老是提示:
System.Data.SqlClient.SqlException: Must declare the variable '@tableName'.
而有明明有申明此變量啊
SqlConnection conn = DBC.DatabaseConnection();
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from @tableName";
cmd.Parameters.Add("@tableName", SqlDbType.NVarChar, 30).Value = DropDownList1.SelectedValue;
SqlDataReader sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
conn.Close();
為什麼運行時老是提示:
System.Data.SqlClient.SqlException: Must declare the variable '@tableName'.
而有明明有申明此變量啊
select * from 'tableName' 多了两个点
SQL不认了
你一定要在传到SqlServer之前把这个表名明确化了才行.
cmd.CommandText = string.Format("select * from {0}", DropDownList1.SelectedValue);