将表格中的列更新为2个不同的值

时间:2019-03-10 20:44:28

标签: sql sql-server

我需要使用2个不同的值(按性别)更新表中的列,但要在1个查询中(仅一次更新)。我有一张桌子,上面有这样的性别的员工:

CREATE TABLE tb_Employee
(
  FNAME nvarchar(50) not NULL,
  LNAME nvarchar(50) not NULL,
  ID int not NULL,
  BDATE date not NULL,
  ADD_STREET nvarchar(50) NULL,
  ADD_NUM nvarchar(50) NULL,
  ADD_CITY nvarchar(50) NULL,
  Gender nvarchar(50) not NULL,
  salary dec(8,2) DEFAULT 0.0,
  PRIMARY KEY(ID),
  constraint Employee_Gender_value check (Gender in('Male','Female'))
)    

insert into tb_Employee values 
('Tom','Cohen',1,'01/2/1990','AA','11','LONDON','Male',4000),
('Pam','Jackson',2,'02/3/1989','BB','11','Delhi','Female',3000),
('John','Labor',3,'03/4/1988','CC','11','Delhi','Male',3500),
('Sam','Kruz',4,'04/5/1987','DD','11','New York','Male',4500),
('Todd','Pit',5,'01/2/1986','EE','11','Delhi','Male',2800),
('Ben','Jonson',6,'01/2/1985','FF','11','LONDON','Male',7000),
('Sara','Parker',7,'01/2/1984','GG','11','LONDON','Male',4800),
('Valiarie','Russell',8,'01/2/1983','HH','11','LONDON','Male',5500),
('James','Ten',9,'01/2/1980','AA','II','New York','Female',6500),
('Russell','Ted',10,'01/2/1978','AA','JJ','New York','Female',8800)

我还有一个类似这样的函数:(它给我一张只包含我发送的性别的员工表)

create function getEmployeeByGender(@gender nvarchar(50))
returns table
as
return (select * from tb_Employee where Gender=@gender)

但我无法在1个查询中更新

update dbo.getEmployeeByGender('Female')
set ADD_STREET = 'bbb'
update dbo.getEmployeeByGender('Male')
set ADD_STREET = 'aaa'

3 个答案:

答案 0 :(得分:3)

您可以使用以下UPDATE,而无需使用功能(只是简单的UPDATEWHERE):

UPDATE tb_Employee 
    SET ADD_STREET = CASE WHEN Gender = 'Male' THEN 'aaa' ELSE 'bbb' END
WHERE Gender IN ('Male', 'Female')
  

demo on dbfiddle.uk

如果您确实需要使用该功能,可以使用INNER JOIN

UPDATE tb_employee SET ADD_STREET = c.ADD_STREET
FROM tb_employee e INNER JOIN (
    SELECT ID, 'aaa' AS ADD_STREET FROM getEmployeeByGender('Male')
    UNION ALL   
    SELECT ID, 'bbb' FROM getEmployeeByGender('Female')
) c ON e.ID = c.ID;
  

demo on dbfiddle.uk

答案 1 :(得分:0)

在更新中使用函数的唯一方法如下-这样做没有任何好处。

update dbo.tb_Employee
  set ADD_STREET = 'bbb'
where id in (select id from dbo.getEmployeeByGender('Female'))

update dbo.tb_Employee
  set ADD_STREET = 'aaa'
where id in (select id from dbo.getEmployeeByGender('Male'))

或以下内容,但又没有好处(至少不是问题的措辞方式)

update dbo.tb_Employee
  set ADD_STREET = case when id in (select id from dbo.getEmployeeByGender('Male')) then 'aaa' else 'bbb' end

答案 2 :(得分:0)

您的函数方式使这种情况更加复杂。但是让我假设您的实际问题并不是那么简单。毕竟,简单的update是最好的方法。

为此,我建议left join

update dbo.tb_Employee
    set ADD_STREET = (cse when f.id is not null then 'bbb' else 'aaa')
    from dbo.tb_Employee e left join
         dbo.getEmployeeByGender('Female') f
         on f.id = e.id left join
         dbo.getEmployeeByGender('Male') m
         on m.id = e.id left join
    where m.id is not null and f.id is not  null