根据查询结果更新字段

时间:2015-11-02 12:19:16

标签: sql sql-server insert

我有两张桌子:

Table 1 - [EmployeeERP]:

[EMER_ID] - My Own Identity - primary key
[EMER_CreateDate]
[EMER_EmployeeID]
[EMER_EmployeeNumber]



Table 2 - [ERP_TEST]:

[ERPT_ID] -  My Own Identity - primary key
[ERPT_EmployeeNumber]
[ERPT_EmployeeID]
[ERPT_IsDuplicate]

我写了这个命令来将数据从一个表转移到另一个表:

INSERT INTO [dbo].[ERP_TEST] ([ERPT_ID],[ERPT_EmployeeNumber],[ERPT_EmployeeID])
select [EMER_ID],[EMER_EmployeeNumber],[EMER_EmployeeID] from [dbo].[EmployeeERP]

后来我写了这个查询:

SELECT * 
FROM (
select [EMER_EmployeeID] , count(*) as cnt
from  [dbo].[EmployeeERP]
group by [EMER_EmployeeID]
) as T
where T.cnt > 1

现在,如果[ERP_TEST]表中的**ERPT_IsDuplicate**重复,我想在字段EMER_EmployeeID的表EmployeeERP中有1(int)否则为0(int)。

你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

如果您希望该标志引用EmployeeERP表中重复的员工ID,那么您可以使用join

update t
    set erpt_isduplicate = (case when e.cnt > 1 then 1 else 0 end)
    from erp_test t left join
         (select [EMER_EmployeeID], count(*) as cnt
          from  [dbo].[EmployeeERP]
          group by [EMER_EmployeeID]
         ) e
         on e.emer_employeeid = t.ERPT_EmployeeID;

我假设您正在使用SQL Server,基于您的语法。