1

背景是我正在建立一个 SQL 连接,该连接需要一个 .csv 文件并将其导入到 SQL Server 数据库表中。

我遇到的问题是,我遇到了查询语法问题,因为我正在导入的 .csv 文件中的一行没有唯一标识符。它需要 3 个字段组合才能使一行唯一/不同。

.csv 文件数据的粗略示例,可以将 .csv 列的前三个列一起考虑以生成唯一行:

Order_Id  Product_Id  Date    Other (etc...)
    1         1a       1/9      q
    1         2a       1/9      q
    1         2a       1/10     e
    2         1a       1/9      e
    2         2a       1/10     e

这是我在 Visual Studios 中简化的查询语法,(我实际上从 .csv 文件中导入了 25 个左右的列,因此为了保持简单/简单,我在 .csv 文件和SQL-Server 表),但基本语法如下所示:

private void SaveImportDataToDatabase(DataTable importData)
{
    using (SqlConnection conn = new SqlConnection("Server=localhost;Database=my_Database;Trusted_Connection=True;"))
    {
        conn.Open();
        foreach (DataRow importRow in importData.Rows)
        {
            
            SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT DISTINCT Order_id, Product_Id, Date FROM Sales WHERE Order_id = @Order_id AND Product_Id = @Product_Id AND Date = @Date) UPDATE SQL_Sales SET Order_id = @Order_id WHERE Order_id = @Order_id ELSE INSERT INTO SQL_Sales (order_id, Product_Id, Date)" +
                                            "VALUES (@order_id, @Product_Id, @Date);", conn);
            
            cmd.Parameters.AddWithValue("@Order_id", importRow["Order_id"]);
            cmd.Parameters.AddWithValue("@Product_Id", importRow["Product_Id"]);
            cmd.Parameters.AddWithValue("@Date", importRow["Date"]);
            
            cmd.ExecuteNonQuery();

        }
    }
}

导入后,我在 SQL Server 表中看到了一些问题,

  1. order_id 字段将为空
  2. 它只导入了非常少量的数据,大约 2000 条记录中的 50 条
  3. 如果我通过 .csv 文件中的更改重新导入数据,比如使用一个新行,我会得到 2000 条记录中的 100 条

我不确定我正在尝试做的事情是否可行或值得。我应该更多地分解它而不是在一个查询中完成所有操作吗?我不一定是编码新手,但我不经常编码/我生疏了,这是我的第一个 C# 项目,所以如果可能的话,请给我一些耐心。

只是想添加更多代码以响应@casey crookston,问题 2 和 3 可能与我的循环有关

private void btnImport_Click(object sender, EventArgs e)
    {
       Cursor = Cursors.WaitCursor;            
       DataTable importData = GetDataFromFile();

        if (importData == null) return;
        SaveImportDataToDatabase(importData);

        MessageBox.Show("Import Successful");
        txtFileName.Text = string.Empty;

        Cursor = Cursors.Default;
    }

    private DataTable GetDataFromFile()
    {
        DataTable importedData = new DataTable();
       try
        {
            using (StreamReader sr = new StreamReader(txtFileName.Text))
            {
                string header = sr.ReadLine();
                if (string.IsNullOrEmpty(header))
                {
                    MessageBox.Show("No File Data");
                    return null;
                }

                string[] headerColumns = header.Split(',');
                foreach (string headerColumn in headerColumns)
                {
                    importedData.Columns.Add(headerColumn);
                }

                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();

                    if (string.IsNullOrEmpty(line)) continue;

                    string[] fields = line.Split(',');
                    DataRow importedRow = importedData.NewRow();

                    for(int i = 1; i < fields.Count(); i++)
                    {
                        importedRow[i] = fields[i];
                    }

                    importedData.Rows.Add(importedRow);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }

        return importedData;
    }
4

1 回答 1

3

这看起来是使用 SQL ServerMERGE语法的好地方:

merge sales s
using (values(@product_id, @order_id, @date, @other_1, @other_2)) 
    as p(order_id, product_id, date, other_1, other_2)
on (s.product_id = p.product_id and s.order_id = p.order_id and s.date = p.date)
when matched then 
    update set s.other_1 = p.other_1, s.other_2 = p.other_2
when not matched by target then 
    insert(order_id, product_id, date, other_1, other_2)
    values(p.order_id, p.product_id, p.date, p.other_1, p.other_2)

这使用前 3 列作为主键;当一个元组已经存在时,列other_1other_2用本来应该插入的值进行更新。

于 2020-09-23T20:10:22.933 回答