SQL参数作为表不起作用

时间:2016-02-24 17:44:01

标签: c# sql sql-server

我想使用此方法返回DataTable,但SqlParameter无效。

Click Here

private DataTable GetTable(string tableName)
{
        const string queryString = "SELECT * FROM @TABLE";

        SqlCommand sqlCommand = new SqlCommand(queryString, _sqlConnection);

        SqlParameter sqlParameter = new SqlParameter("@TABLE", SqlDbType.Text)
        {
            Value = tableName
        };

        sqlCommand.Parameters.Add(sqlParameter);

        _sqlConnection.Open();

        SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
        DataTable dataTable = new DataTable();

        dataAdapter.Fill(dataTable);

        _sqlConnection.Close();
        dataAdapter.Dispose();

        dataGridViewTable.DataSource = dataTable;
        dataGridViewTable.AutoResizeColumns();

        return dataTable;
}

我确信连接成功。另一种方法是工作。这个没有。它会抛出SqlException

Error description

1 个答案:

答案 0 :(得分:2)

您无法将表名作为参数传递。此外,使用using轻松关闭/处置可支配资源。

试试这个......

private DataTable GetTable(string tableName)
{
    string queryString = "SELECT * FROM [" + tableName + "]";

    DataTable dataTable = new DataTable(tableName);
    using (SqlCommand sqlCommand = new SqlCommand(queryString, _sqlConnection))
    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand))
    {
        _sqlConnection.Open();
        dataAdapter.Fill(dataTable);
        _sqlConnection.Close();
    }
    dataGridViewTable.DataSource = dataTable;
    dataGridViewTable.AutoResizeColumns();
    return dataTable;
}

编辑:在查询中为表名添加方括号以处理带空格的名称。