SqlBulkCopy 无法访问表

发布于 2024-12-27 08:09:00 字数 1576 浏览 1 评论 0原文

读入 Excel 工作表(传输表)后,我想使用 SqlBulkCopy 将该数据添加到新表(destinationTable)中,但出现错误:

Cannot access destination table 'test'

我尝试使用默认表名并使用方括号,但是那不起作用。

有什么建议吗?

private void writeToDBButton_Click(object sender, EventArgs e) {
    MakeTable();
    destinationTable.TableName = "test";
    testDBDataSet.Tables.Add("test");

    // Connects to the sql-server using Connection.cs
    SqlConnection connection = Connection.GetConnection();

    using (connection) {
        connection.Open();

        // Uses SqlBulkCopy to copy the data from our transferTable to the destinationTable
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
            bulkCopy.DestinationTableName = destinationTable.TableName;

            try {
                // Write from the source to the destination.
                bulkCopy.WriteToServer(transferTable);
                this.dataGridView2.DataSource = destinationTable;
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }

            connection.Close();
        }
    }
}

private void saveDBButton_Click(object sender, EventArgs e) {
    this.Validate();
    this.usersBindingSource.EndEdit();
    this.tableAdapterManager.UpdateAll(this.testDBDataSet);
}


private void MakeTable() {
    for (int counter = 0; counter < columns; counter++) {
        DataColumn dummy = new DataColumn();
        dummy.DataType = System.Type.GetType("System.Double");
        destinationTable.Columns.Add(dummy);
    }
}

After reading in an excel-sheet (to transferTable), I want to add that data to a new table (destinationTable) using SqlBulkCopy, but I'm getting the error:

Cannot access destination table 'test'

I've tried using the default tablename and using square brackets, but that didn't work.

Any suggestions?

private void writeToDBButton_Click(object sender, EventArgs e) {
    MakeTable();
    destinationTable.TableName = "test";
    testDBDataSet.Tables.Add("test");

    // Connects to the sql-server using Connection.cs
    SqlConnection connection = Connection.GetConnection();

    using (connection) {
        connection.Open();

        // Uses SqlBulkCopy to copy the data from our transferTable to the destinationTable
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
            bulkCopy.DestinationTableName = destinationTable.TableName;

            try {
                // Write from the source to the destination.
                bulkCopy.WriteToServer(transferTable);
                this.dataGridView2.DataSource = destinationTable;
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }

            connection.Close();
        }
    }
}

private void saveDBButton_Click(object sender, EventArgs e) {
    this.Validate();
    this.usersBindingSource.EndEdit();
    this.tableAdapterManager.UpdateAll(this.testDBDataSet);
}


private void MakeTable() {
    for (int counter = 0; counter < columns; counter++) {
        DataColumn dummy = new DataColumn();
        dummy.DataType = System.Type.GetType("System.Double");
        destinationTable.Columns.Add(dummy);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

末が日狂欢 2025-01-03 08:09:01

我通过将临时表更改为 #TmpTable 解决了此错误,一旦我更改了 DestinationTableName 中的名称,它就起作用了!

bulkcopy.DestinationTableName = "#TmpTable";

以前我的临时表为“#TmpTableUpd”

I resolved this error by changing the temp table to #TmpTable, once I changed the name in DestinationTableName it worked!!

bulkcopy.DestinationTableName = "#TmpTable";

Previously I had the temp table as "#TmpTableUpd"

_蜘蛛 2025-01-03 08:09:00

我的问题有点不同,结果我的表名是 SQL 中的保留关键字,所以我必须执行以下操作:

bulkCopy.DestinationTableName = $"{schema}.[{tableName}]";

其中 schema 是目标架构,tableName 是目标表名称

来自 文档

DestinationTableName 是一个由三部分组成的名称 [database].[owningschema].[name]。如果您选择,可以使用其数据库和所属架构来限定表名称。但是,如果表名称使用下划线(“_”)或任何其他特殊字符,则必须使用括号对名称进行转义,如 ([database].[owningschema].[name_01])

My issue was a bit different, turns out my table name was a reserved keyword in SQL so I had to do the following:

bulkCopy.DestinationTableName = $"{schema}.[{tableName}]";

Where schema is the target schema and tableName the target table name

From the documentation

DestinationTableName is a three-part name [database].[owningschema].[name]. You can qualify the table name with its database and owning schema if you choose. However, if the table name uses an underscore ("_") or any other special characters, you must escape the name using surrounding brackets as in ([database].[owningschema].[name_01])

陈独秀 2025-01-03 08:09:00

检查连接到数据库的用户是否

GRANT ALTER ON [dbo].[TABLE_XXX] TO [appuser] 

按照 Jhilden 在 MSDN 论坛

Check that user that connects to db has

GRANT ALTER ON [dbo].[TABLE_XXX] TO [appuser] 

as suggested in answer by Jhilden on MSDN forum.

倥絔 2025-01-03 08:09:00

我最近遇到了同样的错误,并在谷歌搜索答案时发现了这篇文章。我能够通过向正在执行大容量复制命令的用户授予对目标表的插入和选择权限来解决该问题。
最初,我只向用户授予插入权限,并收到“无法访问目标表”错误。

I recently ran into this same error and came across this post while googling for an answer. I was able to solve the problem by giving the user that is executing the bulk copy command insert and select permissions on the destination table.
Originally I had only granted insert permission to the user and got the 'Cannot access destination table' error.

浮华 2025-01-03 08:09:00

执行此代码的用户似乎没有正确访问数据库的权限。
* 检查以便用户获得访问权限。
* 检查您用于连接数据库的连接字符串。

It seems that the user who executes this code don't have proper access to the database.
* Check so that the user got access.
* Check the connectionstring your using to connect to the database.

挽清梦 2025-01-03 08:09:00

我有同样的问题说明

未找到表名对象或权限不足。

它在我的帐户上运行良好,但在最终用户帐户上运行良好,并出现此错误。事实证明,如果您使用 SqlBulkCopyOptions.KeepIdentity 作为选项运行批量复制,连接用户需要 Grant Alter 权限,如果没有,您将收到此不太有用的错误消息。

选项之一是:

  • 从目标表中删除身份
  • 授予该用户在目标表上的更改权限
  • 不使用 KeepIdentity

(这是 Fosna 答案的扩展 但考虑到我花了时间来确定根本原因,我认为可能值得让这个解决方案更明确一些)。

I had the same issue stating

tablename-object not found or insufficient privileges.

It worked fine on my account but not on the end users account, where it gave this error. It turned out that if you run bulkcopy with SqlBulkCopyOptions.KeepIdentity as option, the connection user needs the Grant Alter right, if he doesn't, you will get this not very helpful error message.

options one has:

  • remove Identity from the destination table
  • grant Alter right on destination table for that user
  • not use KeepIdentity

(this is an extension of Fosna's answer but given the time it took me to identify the root cause I thought it might be worth to make this solution a bit more explicit).

疧_╮線 2025-01-03 08:09:00

Bulkcopy 期望该表存在于数据库中。您还应该有权访问该数据库或表。

Bulkcopy expects the table to exists in the database. Also you should have access to this database or table.

止于盛夏 2025-01-03 08:09:00

有趣的是,如果您有一个纯数字的表名,也会发生这种情况。以一个或多个字母字符开头的表名称,效果很好。

Interestingly, this also happens if you have a table name which is purely numeric. Start the table name with one or more alpha characters and it works just fine.

吹梦到西洲 2025-01-03 08:09:00

Andrij Ferents 答案有效。

调用 SQLBulkCopy 之前目标表必须存在。这是新手常见的错误。

Andrij Ferents answer is valid.

The destination table must exist before calling SQLBulkCopy. It is a common newbie mistake.

温柔戏命师 2025-01-03 08:09:00

就我而言,这不是权限问题,而是表名问题中的特殊字符(括号和 & )。

希望这有帮助

In my case, it's not a permission problem, but a special char in the table name problem ( parenthesis and & ).

Hope this helps

戴着白色围巾的女孩 2025-01-03 08:09:00

就我而言,问题是因为现有的 Identity 列

In my case, the problem was because of an existing Identity column

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文