使用连接选项更新SQL Server表

时间:2019-07-17 17:24:11

标签: sql sql-server sql-server-2016

您看到2个表,我想将数据从表Invoice更新/同步到表HR

方案是手动在列HRPO Number中输入数据,然后使用表Invoice更新。我认为这种想法是仅联接表HR中具有现有PO号的数据,如果PO号不存在,则无需获取行。另外,月份列的格式看起来像一个数字,因此,如何在SQL中仅获取月份而与日期格式无关。

enter image description here

2 个答案:

答案 0 :(得分:1)

如果年份 真正 没问题,则可以静态进行。

但是我想您真的想在该HR表中添加一个year字段。

UPDATE INVOICE
  FROM HR
 WHERE INVOICE.po_number = HR.po_number
   SET INVOICE.amount = 
           CASE WHEN INVOICE.MONTH = 20190124 THEN HR.JANUARY
                WHEN INVOICE.MONTH = 20190224 THEN HR.FEBUARY
                WHEN INVOICE.MONTH = 20190324 THEN HR.MARCH
                WHEN INVOICE.MONTH = 20190424 THEN HR.APRIL
                WHEN INVOICE.MONTH = 20190524 THEN HR.MAY
                WHEN INVOICE.MONTH = 20190624 THEN HR.JUNE
                WHEN INVOICE.MONTH = 20190724 THEN HR.JULY
                WHEN INVOICE.MONTH = 20190824 THEN HR.AUGUST
                WHEN INVOICE.MONTH = 20190924 THEN HR.SEPTEMBER
                WHEN INVOICE.MONTH = 20191024 THEN HR.OCTOBER
                WHEN INVOICE.MONTH = 20191124 THEN HR.NOVEMBER
                WHEN INVOICE.MONTH = 20191224 THEN HR.DECEMBER
                ELSE INVOICE.AMOUNT
            END;

答案 1 :(得分:1)

使用数据透视表将发票行转换为列(PO号和月)。然后通过与转换后的表数据结合来更新HR表。