2

我是 SQL Server 的新手。我必须将一个列的值从表 A 复制到另一个表 B 关于另一列(JOIN)但在复制之前我必须检查该值是否存在于另一个表 C 中。如果是,则复制,否则返回其记录值不在表 C 中。我的查询是;

IF EXISTS (SELECT Branch_ID FROM ADM_Branch
INNER JOIN UBL$ on ADM_Branch.Branch_Code = UBL$.[Branch Code  ] 
 WHERE ADM_Branch.Branch_Code = [UBL$].[Branch Code] )

        UPDATE EMP_Personal
    SET Account_Number = UBL$.[Account ] , Bank_ID = 1 , Branch_ID = (select Branch_ID from ADM_Branch join UBL$ on ADM_Branch.Branch_Code = UBL$.[Branch Code  ] where EMP_Personal.Emp_ID = UBL$.[Employee ID  ])
    FROM EMP_Personal JOIN UBL$
    ON EMP_Personal.Emp_ID = UBL$.[Employee ID  ]


ELSE

    ( SELECT UBL$.[Employee ID  ],UBL$.[Name ],UBL$.[Account ],UBL$.[Branch Code  ]
    FROM UBL$) except ( SELECT UBL$.[Employee ID  ],UBL$.[Name ],UBL$.[Account ],UBL$.[Branch Code  ]
    FROM UBL$
    right join ADM_Branch on  ADM_Branch.Branch_Code = UBL$.[Branch Code  ])
4

3 回答 3

1

我认为下面的代码会给你一些想法,我试图保持列名相同,但你可能需要进行一些更改:

UPDATE EMP
SET EMP.Account_Number = UBL.[Account ],
    EMP.Bank_ID = 1,
    EMP.Branch_ID = ADM.Branch_ID   
FROM EMP_Personal EMP
JOIN UBL$ UBL ON EMP_Personal.Emp_ID = UBL.[Employee ID  ]
JOIN ADM_Branch ADM ON ADM.Branch_Code = UBL.[Branch Code  ];

SELECT [Employee ID  ],[Name ],[Account],[Branch Code  ]
FROM UBL$ 
WHERE [Branch Code  ] NOT IN (SELECT Branch_Code FROM ADM_Branch);
于 2013-07-17T13:14:35.453 回答
1

对于有条件的 INSERT/UPDATE/DELETE,最好使用 MERGE 语句。它的语法一开始并不容易,最后的语句很长,但这是一个非常强大的工具。我建议你学习它。MERGE 可在 MS SQL Server 2008 和更高版本中访问。

于 2013-07-17T11:59:52.327 回答
1

谢谢我以这种方式所做的一切;

UPDATE EMP_Personal
SET account_number = s.[Account ] , Bank_ID = 1 , Branch_ID= (select Branch_ID from ADM_Branch join UBL$ on ADM_Branch.Branch_Code = UBL$.[Branch Code  ] where EMP_Personal.Emp_ID = UBL$.[Employee ID  ])
FROM emp_personal
INNER JOIN (
SELECT UBL$.[Account ] , UBL$.[Employee ID  ]
FROM UBL$
INNER JOIN adm_branch
ON adm_branch.branch_code = UBL$.[Branch Code  ] ) as s
ON s.[Employee ID  ] = emp_personal.Emp_ID
于 2013-07-18T08:05:13.113 回答