0

我有一个表(Customer_Master_File),需要从转储到文件夹中的平面文件中进行更新。我有一个 SSIS 包,可以运行以获取平面文件并将它们导入临时表(temp_Customer_Master_File)

我一直无法做到的是:

对于 temp 表中的每条记录,如果 Master 表中存在 Customer_Number,则更新它,如果不插入 temp 表的内容。

我正在更新记录的所有字段,而不是查找单个字段的更改。

我尝试了 SQL Merge 功能,但是当源数据中有多个记录时它会出错。

平面文件包含对客户记录的更改,一次可能有多个更改。我只想根据需要通过插入或更新来处理每条记录。

我还尝试从 TEMP_TABLE WHERE CUSTOMER_NUMBER NOT IN MASTER_FILE 执行 INSERT INTO MASTER_FILE,但是当它遇到重复的源行时,这也会失败并出现 PK 错误。

4

1 回答 1

3
UPDATE m SET 
  col2 = t.col2, 
  col3 = t.col3 -- etc. - all columns except Customer_Number
FROM dbo.Master_File AS m
INNER JOIN 
(
  SELECT 
    Customer_Number, rn = ROW_NUMBER() OVER
    (
      PARTITION BY Customer_Number ORDER BY [timestamp_column] DESC
    ), col2, col3, ... etc ...
  FROM dbo.Temp_Table
) AS t
ON m.Customer_Number = t.Customer_Number
WHERE t.rn = 1;

INSERT dbo.Master_File(Customer_Number, col2, col3, ...etc...)
  SELECT Customer_Number, col2, col3, ...etc...
  FROM 
  (
    SELECT 
      Customer_Number, rn = ROW_NUMBER() OVER 
      (
        PARTITION BY Customer_Number ORDER BY [timestamp_column DESC
      ),
      col2, col3, ...etc...
    FROM dbo.Temp_Table AS t 
    WHERE NOT EXISTS 
    (
      SELECT 1 FROM dbo.Master_File AS m
      WHERE m.Customer_Number = t.Customer_Number
    )
  ) AS x WHERE rn = 1;

这会处理源表中不存在于目标中的多行。我对必须调整的列名做出了假设。

MERGE可能很诱人,但是我回避它有几个原因:

  1. 语法令人生畏并且难以记忆......
  2. 除非您有意添加特定的锁定提示,否则您不会获得比上述方法更多的并发性...
  3. 有许多未解决的错误,MERGE可能还有更多尚未被发现的错误......

我最近也在这里发布了一个警告提示,并在这里收集了一些其他意见

于 2013-04-14T21:44:40.393 回答