这可以简单说明吗?

时间:2016-11-03 03:31:43

标签: sql sql-server

如何简化此代码?只需将整个Null列更新为具有相应ID的名称。

update salesman 
set name = 'James Hoog'
where salesman_id = 5001

update salesman
set name = 'Nail Knite' 
where salesman_id = 5002

update salesman
set name = 'Pit Alex'
where Salesman_id = 5005

update salesman
set name = 'Mc Lyon' 
where salesman_id = 5006

4 个答案:

答案 0 :(得分:5)

使用CASE语句标识每个NAME

salesman_id

试试这种方式

UPDATE salesman 
SET    NAME = CASE salesman_id 
                WHEN 5001 THEN 'James Hoog' 
                WHEN 5002 THEN 'Nail Knite' 
                WHEN 5005 THEN 'Pit Alex' 
                WHEN 5006 THEN 'Mc Lyon' 
              END 
WHERE  salesman_id IN ( 5001, 5002, 5005, 5006 ) 

答案 1 :(得分:2)

如果您在另一个表中有名称和ID,则执行UPDATE / JOIN

vi

答案 2 :(得分:2)

尝试MERGE

MERGE salesman AS t
USING (VALUES
    (5001, 'James Hoog'),
    (5002, 'Nail Knite'),
    (5005, 'Pit Alex'),
    (5006, 'Mc Lyon'))
    AS s (salesmain_id, name)
ON (t.salesman_id = s.salesman_id)
WHEN MATCHED THEN
    UPDATE SET name = s.name;

答案 3 :(得分:0)

UPDATE salesman SET
      NAME = CASE WHEN salesman_id = 5001 THEN 'James Hoog' 
                  WHEN salesman_id = 5002 THEN 'Nail Knite' 
                  WHEN salesman_id = 5005 THEN 'Pit Alex' 
                  WHEN salesman_id = 5006 THEN 'Mc Lyon' END
WHERE salesman_id IN (5001,5002,5005,5006)