ggt*_*ffg 1 sql sql-server sql-server-2008
我需要使用不同的键更新两行的列值.约束是我想在单个查询中执行此操作.
例如:
Coll1 Coll2
---------------
A 1
B 2
C 3
Run Code Online (Sandbox Code Playgroud)
应该是这样的
Coll1 Coll2
--------------
A 3
B 2
C 1
Run Code Online (Sandbox Code Playgroud)
使用case表达式:
update t
set Coll2 = case when Coll1 = 'A' then 3 else 1 end
where Coll1 in ('A','C')
Run Code Online (Sandbox Code Playgroud)
rextester演示:http://rextester.com/HUBDAP9516
收益:
+-------+-------+
| Coll1 | Coll2 |
+-------+-------+
| A | 3 |
| B | 2 |
| C | 1 |
+-------+-------+
Run Code Online (Sandbox Code Playgroud)
更新参数化版本:
declare @key1 char(1) = 'A';
declare @key2 char(1) = 'C';
update t
set t.Coll2 = x.Coll2
from t
inner join t x
on t.Coll1 <> x.Coll1
and t.Coll1 in (@key1,@key2)
and x.Coll1 in (@key1,@key2)
Run Code Online (Sandbox Code Playgroud)
rextester演示:http://rextester.com/PKQSAV63963
收益:
+-------+-------+
| Coll1 | Coll2 |
+-------+-------+
| A | 3 |
| B | 2 |
| C | 1 |
+-------+-------+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
566 次 |
| 最近记录: |