2010-02-10 56 views
2

如何交换SQL中的记录。我有一个案例,我必须将一个员工的记录交换到另一个员工,例如我必须更新,如“B的头上戴着帽子”,A头上戴着B的帽子“。 只有我需要查询,我有领域。这应该是什么问题?

什么应该是最好的方法呢?有没有简单的查询呢?

+8

您应该为您的许多问题接受一些答案,并在问题中添加一些示例数据。 – 2010-02-10 11:49:36

+1

你需要更具体。显示你的模式,一些例子元组,你已经尝试了什么,以及你想要结果是什么。 – 2010-02-10 11:51:35

+0

您可以使用RDBMS提供的过程语言。然后像使用任何通用语言一样使用临时变量并交换数据。 – 2010-02-10 11:52:04

回答

2
declare @hatIdA int 
declare @hatIdB int 

select @hatIdA = hatId from employees where empID = 'A' 

select @hatIdB = hatId from employees where empID = 'B' 

update employees set hadId = @hatIdB where empID = 'A' 

update employees set hadId = @hatIdA where empID = 'B' 

我会做这样......

3

帽子和员工 'A' 和 'B' 例如,在雇员表使用self-join为MySQL:

UPDATE 
    employees AS e1 
JOIN 
    employees AS e2 ON (e1.employee_id = 'A' AND e2.employee_id = 'B') 
SET 
    e1.hat = e2.hat, 
    e2.hat = e1.hat; 

延伸阅读:

+0

我可以在SQL中做到这一点吗? – ahmed 2010-02-10 12:12:10

+0

这个很酷!但我如何在SQL中执行此操作,我正在使用sql 2000 – ahmed 2010-02-10 12:13:15