SQL查询以使用同一表中不同列中另一行的值更新行中的值

时间:2015-11-18 23:47:24

标签: sql-server

我有下表:

RID|Response|CV1|CV2|SR1|PF1|FD1|
====================================
1 |feedback | 0 | 0 | 0 | 0 | 1 |
2 |comment_ | 0 | 0 | 0 | 0 | 1 |
3 |2ice wkly| 0 | 0 | 0 | 1 | 0 |
4 |CV1|table| 1 | 0 | 0 | 0 | 0 |
5 |CV2|frame| 0 | 1 | 0 | 0 | 0 | 
6 |Poor     | 0 | 0 | 1 | 0 | 0 |

我想用管道(|)更新具有相应响应值的所有1个值和所有响应值。我想用条形后面的部分替换值,所以我的结果表如下所示:

RID|Response | CV1 | CV2 | SR1|   PF1   |   FD1  |
==================================================
1  |feedback |  0  |  0  |  0 |    0    |feedback|
2  |comment_ |  0  |  0  |  0 |    0    |comment_|
3  |2ice wkly|  0  |  0  |  0 |2ice wkly|   0    |
4  |CV1|table|table|  0  |  0 |    0    |   0    |
5  |CV2|frame|  0  |frame|  0 |    0    |   0    | 
6  |Poor     |  0  |  0  |Poor|    0    |   0    |

2 个答案:

答案 0 :(得分:0)

尝试此更新声明 -

UPDATE tblname SET CV1 = CASE CV1 WHEN 1 THEN SUBSTRING(Response,CHARINDEX('|',Response)+1,LEN(Response)) ELSE CV1 END,
                   CV2 = CASE CV2 WHEN 1 THEN SUBSTRING(Response,CHARINDEX('|',Response)+1,LEN(Response)) ELSE CV2 END,
                   SR1 = CASE SR1 WHEN 1 THEN SUBSTRING(Response,CHARINDEX('|',Response)+1,LEN(Response))ELSE SR1 END,
                   PF1 = CASE PF1 WHEN 1 THEN SUBSTRING(Response,CHARINDEX('|',Response)+1,LEN(Response)) ELSE PF1 END,
                   FD1 = CASE FD1 WHEN 1 THEN SUBSTRING(Response,CHARINDEX('|',Response)+1,LEN(Response)) ELSE FD1 END

答案 1 :(得分:0)

如果您的字段不是VARCHAR / NVARCHAR,请更改表格以便它们显示。

否则,只需像这样更新表格:

UPDATE tblName
SET [CV1] = CASE [CV1] WHEN '1' THEN RIGHT([Response], LEN([Response]) - CHARINDEX('|', [Response])) ELSE '0' END
  , [CV2] = CASE [CV2] WHEN '1' THEN RIGHT([Response], LEN([Response]) - CHARINDEX('|', [Response])) ELSE '0' END
  , [SR1] = CASE [SR1] WHEN '1' THEN RIGHT([Response], LEN([Response]) - CHARINDEX('|', [Response])) ELSE '0' END
  , [PF1] = CASE [PF1] WHEN '1' THEN RIGHT([Response], LEN([Response]) - CHARINDEX('|', [Response])) ELSE '0' END
  , [FD1] = CASE [FD1] WHEN '1' THEN RIGHT([Response], LEN([Response]) - CHARINDEX('|', [Response])) ELSE '0' END