检查另一个表sql中是否存在列的值

时间:2013-07-17 11:50:59

标签: sql sql-server

我是SQL Server的新手。 我将相对于另一列(JOIN)将表A的值从表A复制到另一个表B. 但在复制之前,我必须检查该值是否存在于另一个表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  ])

3 个答案:

答案 0 :(得分:1)

对于条件INSERT / UPDATE / DELETE,使用MERGE语句要好得多。它的语法起初并不容易,最后的陈述很长,但这是非常强大的工具。我建议你去学习它。可以在MS SQL Server 2008及更高版本中访问MERGE。

答案 1 :(得分: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);

答案 2 :(得分: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