我尝试将数据从 DB1 复制到 DB2。但出现错误:必须声明表变量“@TableName”。
这段代码有什么问题?
函数:
public void TransferData()
{
SqlConnection source = new SqlConnection(strConnectDB1);
SqlConnection destination = new SqlConnection(strConnectDB2);
source.Open();
destination.Open();
SqlCommand cmd= new SqlCommand("SELECT * FROM @TableName", source);
cmd.Parameters.AddWithValue("@TableName", listbox1.SelectedItem.ToString());
SqlDataReader reader = cmd.ExecuteReader();
SqlBulkCopy bulkData = new SqlBulkCopy(destination);
bulkData.DestinationTableName = listbox1.SelectedItem.ToString();
bulkData.WriteToServer(reader);
.
.
}
按钮:
private void button5_Click(object sender, EventArgs e)
{
CreateTableName();
TransferData();
}
最佳答案
SQL FROM
子句中的表名不是表达式,因此不能在参数中发送。
您需要手动构造 SQL 字符串,例如
SqlCommand cmd = new SqlCommand(string.Format("SELECT * FROM {0}", listbox1.SelectedItem), source);
我强烈建议您分隔表名以防止 SQL 注入(inject)攻击。
SqlCommand cmd = new SqlCommand(string.Format("SELECT * FROM {0}", "[" + listbox1.SelectedItem.ToString().Replace("]", "]]") + "]"), source);
关于c# - 必须声明表变量 "@"。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21699842/