根据第一个表

时间:2017-10-11 13:04:32

标签: sql-server tsql

我有两张桌子。我必须根据第一个表格和INVE_KEYEVEN_KEY的记录插入或更新第二个表格(两者的组合必须是唯一的)。

第一张表= @ tbl1

第二张表= @ tbl2

示例1:

  

如果第二个表alredy的INVE_KEY = 1,EVEN_KEY = 2,并且第一个表有   INVE_KEY = 1,EVEN_KEY = 2,此行仅在第二个表(列中)中更新   QUA)。

示例2:

  

如果第二个表没有INVE_KEY = 3,EVEN_KEY = 1,那么这一行就会出现   从第一张表插入第二张表。

我的问题是我不知道如何从表到表插入,同时检查第二个表中是否存在每个记录?

第一张表:

+----------+----------+-----+
| INVE_KEY | EVEN_KEY | QUA |
+----------+----------+-----+
|        1 |        1 |   3 |
|        2 |        1 |   4 |
|        3 |        1 |   5 |
|        4 |        1 |   6 |
+----------+----------+-----+

第二张表:

+----------+----------+-----+
| INVE_KEY | EVEN_KEY | QUA |
+----------+----------+-----+
|        3 |        1 |   0 |
|        4 |        1 |   0 |
+----------+----------+-----+

更新第二个表后,预期结果:

+----------+----------+-----+
| INVE_KEY | EVEN_KEY | QUA |
+----------+----------+-----+
|        1 |        1 |   3 |(inserted)
|        2 |        1 |   4 |(inserted)
|        3 |        1 |   5 |(updated QUA)
|        4 |        1 |   6 |(updated QUA)
+----------+----------+-----+

两个表的创建和数据:

declare @tbl1 table
          (
            INVE_KEY INT,
            EVEN_KEY INT,
            QUA INT
          )

          declare @tbl2 table
          (
            INVE_KEY INT,
            EVEN_KEY INT,
            QUA INT
          )


          insert into @tbl1(inve_Key, even_Key, qua)
          values(1, 1, 3),(2,1,4),(3,1,5),(4,1,6)

          insert into @tbl2(inve_Key, even_Key, qua)
          values(3,1,0),(4,1,0)

1 个答案:

答案 0 :(得分:1)

试一试

  MERGE INTO TargetTable AS TargetTable
  USING SourceTable AS SourceTable
  ON (TargetTable.INVE_KEY = SourceTable.INVE_KEY) -- business keys only
     and (TargetTable.EVEN_KEY = SourceTable.EVEN_KEY)
  -- Insert the new rows
  WHEN NOT MATCHED --  New records 
  THEN
    INSERT ( INVE_KEY,
             EVEN_KEY,
             QUA

             )
    VALUES  
  (        SourceTable.INVE_KEY,
             SourceTable.EVEN_KEY,
-- Updates

  WHEN MATCHED AND ( TargetTable.QUA <> SourceTable.QUA
            ) THEN

    UPDATE SET  
  TargetTable.QUA = SourceTableQUA ;