【发布时间】:2020-09-23 12:39:38
【问题描述】:
我正在创建临时表:
var sql = $@"
CREATE TABLE #tempImport (Year datetime NULL,
Spend decimal (19, 5) NULL, UserId int NULL, Product nvarchar(255) NULL, Margin decimal (19, 5) NULL,
ClientId int NOT NULL, Id int IDENTITY(1,1) NOT NULL);";
然后我访问它:
var sqlConn = new SqlConnection();
sqlConn.ConnectionString = conn;
using (var connection = new SqlConnection(conn))
{
using (SqlCommand command = new SqlCommand("", connection))
{
try
{
connection.Open();
//Creating temp table on database
command.CommandText = sql;
command.ExecuteNonQuery();
//Bulk insert into temp table
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(conn))
{
bulkcopy.BulkCopyTimeout = 660;
bulkcopy.DestinationTableName = "#tempImport";
bulkcopy.WriteToServer(reader);
bulkcopy.Close();
}
// Updating destination table, and dropping temp table
command.CommandText = mergeScript;
command.ExecuteNonQuery();
}
catch (Exception ex)
{
// Handle exception properly
}
finally
{
connection.Close();
}
}
但是我在bulkcopy.WriteToServer(reader); 上遇到异常:
System.InvalidOperationException: Cannot access destination table '#tempImport'.
---> System.Data.SqlClient.SqlException (0x80131904): Invalid object name '#tempImport'.
这是为什么呢?我想我发现的所有例子都是这样使用的,
【问题讨论】:
-
我认为它的本地临时表和 BulkCopy 是不同的连接,所以表直到那个时候才消失。要么您必须使用相同的连接,要么您可以使用 ## 创建全局临时表,但您必须稍后将其删除
标签: c# sql sql-server .net-core azure-sql-database