我想在 Microsoft SQL Server 中的两个不同行中交换列的值

2021-09-10 00:00:00 tsql sql-server

我想在 Microsoft SQL SERVER 中做以下两个 SQL 查询

I want to do the following two SQL Queries in Microsoft SQL SERVER

UPDATE Partnerships SET sortOrder = 2 WHERE sortOrder = 1;
UPDATE Partnerships SET sortOrder = 1 WHERE sortOrder = 2;

唯一的问题是,我不允许 sortOrder 包含相同的值,它是一个唯一键.我怎么能解决这个问题,因为第一个查询违反了唯一键规则并终止了?还是我必须摆脱我拥有的唯一键规则?

The only problem is, I don't allow for sortOrder to contain the same value, it is a unique key. How could I get around this, because the first query violates the unique key rule and terminates? Or will I have to get rid of the unique key rule I have?

谢谢!

推荐答案

使用 CASE 并一次性完成两行.每个过滤键值需要一个 CASE 子句:

Use a CASE and do both rows in one go. You'd need one CASE clause per filter key value:

UPDATE Partnerships
SET sortOrder = CASE WHEN sortOrder = 1 THEN 2 ELSE 1 END
WHERE sortOrder IN (1, 2)

有点厚脸皮:

UPDATE Partnerships
SET sortOrder = 3-sortOrder
WHERE sortOrder IN (1, 2)

相关文章