我正在创建临时表:
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'.
为什么?我想我找到的所有例子都是这样用的,
1条答案
按热度按时间wlzqhblo1#
它的本地温度表和
SqlBulkCopy
是不同的连接,所以表直到那个时候才消失。必须使用相同的连接,或者可以使用##
但你以后必须删除它。