将csv文件读取到数据表并传递到存储过程

时间:2018-12-13 20:34:01

标签: c# sql sql-server stored-procedures

我有一个csv文件,其中包含80多个列和3000多个行。我的列都在标题(name1name2name3name4)中,这很好。我的错误是,它没有计算我的所有行并将其添加到数据库中。.我希望我的流阅读器或任何其他推荐的标头跳过第一条记录,因为它填充了列名。然后添加数据行。

using (StreamReader sr = new StreamReader(filename))
            {
                //this assume the first record is filled with the column names

                    string[] headers = sr.ReadLine().Split(',');
                    foreach (string header in headers)
                    {
                        tvp.Columns.Add(header);
                    }
                    while (!sr.EndOfStream)
                    {
                        string[] rows = sr.ReadLine().Split(',');
                        //Create a new row
                        DataRow dr = tvp.NewRow();
                        for (int i = 0; i < headers.Length; i++)
                        {
                            dr[i] = rows[i];
                        }
                        tvp.Rows.Add(dr);
                       // Console.WriteLine(tvp);
                    }               
            }

            //Passing a Table-Valued Parameter to a Stored Procedure
            using (SqlConnection con = new SqlConnection(Connectionstring))
            {
                con.Open();
                //Execute the cmd
                // Configure the command and sql parameter. 
                SqlCommand cmd = new SqlCommand("dbo.DataTable", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = 5000;

                // Create a DataTable with the modified rows.  
                DataTable addedCategories = tvp.GetChanges(DataRowState.Added);
                // these next lines are important to map the C# DataTable object to the correct SQL User Defined Type
                SqlParameter tvparam = cmd.Parameters.AddWithValue("@dt", tvp);
                tvparam.SqlDbType = SqlDbType.Structured;
                tvparam.TypeName = "dbo.DataTableType";
                //SqlParameter parameter = new SqlParameter("@dt", SqlDbType.Structured)
                cmd.Parameters.AddWithValue("@fy", drlFY.SelectedValue);
                cmd.Parameters.AddWithValue("@offid", drlOfficeID.SelectedValue);
                cmd.Parameters.AddWithValue("@updateBy", "9999");
                cmd.Parameters.AddWithValue("@sourcefile", strSrcFile);

                // Execute the command
                cmd.ExecuteNonQuery();
                con.Close();

1 个答案:

答案 0 :(得分:0)

对于从CSV文件导入数据的具体要求我不清楚,但是批量导入是您的选择。在以下位置签出:https://docs.microsoft.com/en-us/sql/relational-databases/import-export/import-bulk-data-by-using-bulk-insert-or-openrowset-bulk-sql-server?view=sql-server-2017