使用现有表架构动态创建临时表(在SQL中)以添加新记录(来自excel)

时间:2018-07-09 16:15:35

标签: c# sql-server excel visual-studio

我是C#的新手,我正在构建一个项目以使用excel添加/更新sql表。我有一种使用参数化查询将excel数据添加到现有表中的方法,但是我正在寻找一种动态的方法(我将使用操纵多个表)。这是我正在使用的当前代码。

我的错误出现在

附近
bulkcopy.WriteToServer(reader); 

我了解到using语句完成后会处理对象,该如何解决呢?

private void button3_Click(object sender, EventArgs e)
    {
        String connection = @"Data Source=server;Initial Catalog=database;Integrated Security=True";

        using (var connection = new SqlConnection(connectionString))
        {
            var command = connection.CreateCommand();
            // This will return the table schema information
            command.CommandText = "select * from information_schema.columns where table_name = @tableName";
            command.Parameters.Add("@tableName", SqlDbType.VarChar).Value = "MyTable";
            command.CommandType = CommandType.Text;

            connection.Open();
            var columnList = new List<ColumnInfo>();
            // Loop over the results and create a ColumnInfo object for each Column in the schema.
            using (IDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo))
            {
                while (reader.Read())
                {
                    columnList.Add(new ColumnInfo().ReadFromReader(reader));
                }
            }

            string createTempCommand = "create table {0} ({1})";
            StringBuilder sb = new StringBuilder();
            // Loop over each column info object and construct the string needed for the SQL script.
            foreach (var column in columnList)
            {
                sb.Append(column.ToString());
            }

            // create temp table
            command.CommandText = string.Format(createTempCommand, "#TempTable",
                                  string.Join(",", columnList.Select(c => c.ToString()).ToArray()));
            command.ExecuteNonQuery();
            //var dataTable = new System.Data.DataTable();
            // dataTable.Load(reader);

            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
            {
                bulkCopy.DestinationTableName = "#TempTable";
                bulkCopy.WriteToServer(reader);
            }

            // update for rows/values
            //public class ColumnInfo
        }
    }

    public class ColumnInfo
    {
        public string Name { get; set; }
        public string DataType { get; set; }
        public int OrdinalPosition { get; set; }
        public bool IsNullable { get; set; }
        public string MaxLength { get; set; }

        protected string MaxLengthFormatted
        {
            // note that columns with a max length return –1.
            get { return MaxLength.Equals("-1") ? "max" : MaxLength; }
        }

        public ColumnInfo ReadFromReader(IDataReader reader)
        {
            // get the necessary information from the datareader.
            // run the SQL on your database to see all the other information available.
            this.Name = reader["COLUMN_NAME"].ToString();
            this.DataType = reader["DATA_TYPE"].ToString();
            this.OrdinalPosition = (int)reader["ORDINAL_POSITION"];
            this.IsNullable = ((string)reader["IS_NULLABLE"]) == "YES";
            this.MaxLength = reader["CHARACTER_MAXIMUM_LENGTH"].ToString();
            return this;
        }

        public override string ToString()
        {
            return string.Format("[{0}] {1}{2} {3}NULL", Name, DataType,
                MaxLength == string.Empty ? "" : "(" + MaxLengthFormatted + ")",
                IsNullable ? "" : "NOT ");
        }
    }

0 个答案:

没有答案