从 CSV 导入时更新现有列值并在 SQL 中不存在的记录中插入新值

update existing column values and insert new in record doesn't exist in SQL when importing from CSV

你能帮我跟进吗?

我们有在 SQL 服务器上运行的薪资软件。我必须从 SQL 服务器更新某些工资单类别,以便它可以反映在软件上。

这是我的 Excel 文件:

Employee Number  Payroll Category  Rate
------------------------------------------
111111           011               32.21
111111           012               56.23
111111           013               12.52
111111           021               45.21
111112           011               36.21
111112           012               56.23
111112           013               42.54
111112           021               85.21

这些是我数据库中的当前值 table Masterpaycard

 Employee Number     Payroll Category  Rate
 -------------------------------------------
    111111           011               0.00
    111111           012               0.00
    111111           013               10.25

    111112           011               36.21
    111112           012               12.50
    111112           013               41.25
    111112           021               85.21

因此,如果您看到以下记录不存在于数据库中,但存在于 .CSV 中,那么我必须插入它。

 111111           021               45.21

此处的员工编号和薪资类别是来自 EmployeePayroll Category table 的 FK。

所以我的最终结果在数据库和前端应该是这样的。

Employee Number    Payroll Category    Rate
--------------------------------------------
    111111           011               32.21
    111111           012               56.23
    111111           013               12.52
    111111           021               45.21
    111112           011               36.21
    111112           012               56.23
    111112           013               42.54
    111112           021               85.21

我想用简单的话来说,如果 MASTERPAYCARD table 中的工资单类别匹配,那么只需使用 .CSV 中的值更新类别,如果我们找不到 Payrollcategory,则将其插入为该员工的新类别并从 CSV 中增加价值。

请帮忙。

这是您需要采取的方法类型...

create table #Table1 (
    id int,
    value varchar(10)
)

create table #Table2 (
    id int,
    value varchar(10)
)

insert into #Table1 values (1, 'AAA')
insert into #Table1 values (2, 'BBB')

insert into #Table2 values (1, 'ZZZ')
insert into #Table2 values (3, 'CCC')

select * from #Table1
select * from #Table2

--insert data from Table2 into Table1 if it doesn't already exist in Table1
insert into #Table1 
select #Table2.* from #Table2
left join #Table1 on #Table2.id = #Table1.id
where #Table1.id is null

--update data in Table1 from Table2 if it does already exist in Table1
update #Table1 set value = #Table2.value
from #Table2
left join #Table1 on #Table2.id = #Table1.id
where #Table1.id is not null

select * from #Table1