使用case语句更新

时间:2013-10-07 21:09:03

标签: sql sql-server sql-server-2008

给出一张表:

ColumnPosition, ColumnName
   Col 1,          NULL
   Col 2,          NULL
   Col 3,          NULL

我想根据基于ColumnPosition的预定义值映射更新ColumnName

例如:
如果ColumnPosition ='Col 1',则将ColumnName更新为'Name' 如果ColumnPosition ='Col 3',则将ColumnName更新为'Address'

如何使用CASE语句完成?

2 个答案:

答案 0 :(得分:6)

我认为您的意思是UPDATE而不是INSERT

UPDATE MyTable
SET ColumnName = CASE WHEN ColumnPosition = 'Col 1' THEN 'Name'
                      WHEN ColumnPosition = 'Col 3' THEN 'Address'
                      -- ... the rest of your conditions
                      ELSE -- put your default value here
                 END

答案 1 :(得分:5)

您可以设置地图然后进行连接

,而不是做一堆案例陈述
With Map as 
(
    SELECT       'Col 1' ColumnPosition , 'Name' as ColumnName
    UNION SELECT 'Col 3' , 'Address'
 )
UPDATE Table1 
SET Table1.ColumnName = Map.ColumnName
FROM
  table1  
  INNER JOIN MAP 
  ON Table1.ColumnPosition = Map.ColumnPosition;

DEMO