Skip to content

Commit

Permalink
Fix for when sql bulk insert into temp table
Browse files Browse the repository at this point in the history
  • Loading branch information
nh43de committed Aug 29, 2023
1 parent 4908414 commit 8c16777
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -16,7 +16,7 @@ It also provides a powerful API for filtering and object materialization.

- Date string parsing
- Shallow comparisons
- Bulk inserts
- Generate SqlBulkCopy automatically for high-performance bulk inserts
- Fit table/CSV to SQL table
- SQLite Bulk operations
- Minimal dependencies
Expand Down
26 changes: 23 additions & 3 deletions src/DataPowerTools/PowerTools/Database.cs
Expand Up @@ -4,6 +4,7 @@
using System.Data.Common;
using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using DataPowerTools.DataReaderExtensibility.Columns;
Expand Down Expand Up @@ -721,6 +722,19 @@ public static string[] GetNonComputedColumns(string tableName, string connection
}
}

static bool IsTempTableName(string tableName)
{
// Regex pattern to match temporary table names starting with '#'
var pattern = @"^\[?#(\w+)";

// Create a regex object and match the input tableName
var regex = new Regex(pattern);
var match = regex.Match(tableName);

// Return true if the input matches the pattern, indicating it's a temp table name
return match.Success;
}

/// <summary>
/// Gets the columns of a table that are not computed columns.
/// </summary>
Expand All @@ -732,16 +746,22 @@ public static string[] GetNonComputedColumns(string tableName, SqlConnection con
//TODO: this is duplicated in MsSqlDatabaseConnection and sqlocity.database
var dt = new DataTable();

var isTempTable = IsTempTableName(tableName);

var table = isTempTable ? "tempdb.." + tableName : tableName;

var tempDbQualifier = isTempTable ? "tempdb." : "";

try
{
using (var sc = new SqlCommand(@"select name, column_id from sys.all_columns a
using (var sc = new SqlCommand(@$"select name, column_id from {tempDbQualifier}sys.all_columns a
where a.object_id = OBJECT_ID(@table_name)
except
select name, column_id from sys.computed_columns a
select name, column_id from {tempDbQualifier}sys.computed_columns a
where a.object_id = OBJECT_ID(@table_name)
order by column_id", connection))
{
sc.Parameters.Add(new SqlParameter("@table_name", tableName));
sc.Parameters.Add(new SqlParameter("@table_name", table));

using (var sa = new SqlDataAdapter(sc))
{
Expand Down

0 comments on commit 8c16777

Please sign in to comment.