没有现有目标表的SqlBulkCopy.WriteToServer

时间:2017-07-30 18:55:01

标签: c# sql-server

是否可以将 using (SqlBulkCopy bc = new SqlBulkCopy(TheConnString, options)) { bc.DestinationTableName = destTableName; bc.WriteToServer(theTable); // Problem is theTable doesnt exist on database yet! } 转储到尚不存在的SQL Server目标表中?我意识到一个选项是手动创建表,但我从用户输入的CSV导入,所以我没有列的先验知识。

sqlCon

1 个答案:

答案 0 :(得分:1)

这里有一些代码可以帮助您动态创建表格:

    static string GetSqlType(Type dataTableColunmType)
    {
        //per type mappings here 
        //https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings
        if (dataTableColunmType == typeof(string))
        {
            return "nvarchar(max)";
        }
        else if (dataTableColunmType == typeof(int))
        {
            return "int";
        }
        else if (dataTableColunmType == typeof(Single))
        {
            return "real";
        }
        else if (dataTableColunmType == typeof(double))
        {
            return "float";
        }
        else if (dataTableColunmType == typeof(DateTime))
        {
            return "datetime";
        }
        else if (dataTableColunmType == typeof(byte[]))
        {
            return "varbinary(max)";
        }
        else
        {
            throw new NotSupportedException($"Type {dataTableColunmType.Name} not supported");
        }


    }
    static string GetCreateTableDDL(string tableName, DataTable table)
    {
        var ddl = new StringBuilder();
        ddl.AppendLine($"create table [{tableName}] (");
        foreach (DataColumn col in table.Columns)
        {
            ddl.Append($"  [{col.ColumnName}] {GetSqlType(col.DataType)}, ");
        }
        ddl.Length = ddl.Length - ", ".Length;
        ddl.Append(")");

        return ddl.ToString();
    }
相关问题