简体   繁体   English

在SQL中更改PK值

[英]Change PK value in SQL

May be this question is duplicate.I check up this answer for my problem.But nothing of them solve my problem. 可能这个问题是重复的。我检查了这个问题的答案,但是没有一个解决我的问题。 Finally my question like it. 最后我的问题就这样了。 I have a person table like it. 我有一个像这样的人桌。 在此处输入图片说明 I want to change ID=99980 and ID=99982 with each other. 我想彼此更改ID = 99980和ID = 99982。 ID is PK and auto increment. ID为PK,自动递增。

You mean you want to ex -change them? 你的意思是你要 -CHANGE呢?

If so, you can do it like this: 如果是这样,您可以这样做:

UPDATE YOUR_TABLE
SET ID =
    CASE ID
    WHEN 99980 THEN 99982
    ELSE 99980
    END
WHERE ID IN (99980, 99982);

[SQL Fiddle] [SQL提琴]

  • This works out-of-box if the DBMS enforces constraints when the SQL command finishes (Oracle and MS SQL Server). 如果DBMS在SQL命令完成时强制执行约束(Oracle和MS SQL Server),则此操作即开即用。
  • If the DBMS enforces constraints during command execution, but also supports deferred constraints, it can be made to work by by deferring the key on ID (PostgreSQL). 如果DBMS 命令执行期间强制执行约束,但也支持延迟约束,则可以通过延迟ID(PostgreSQL)上的键来使其工作。
  • On a DBMS that supports neither (MySQL), you'll have to split it to 3 UPDATES using a known unoccupied ID as an intermediary, for example: 99980 -> -1, 99982 -> 99980, -1 -> 99982. 在不支持两者的DBMS(MySQL)上,您必须使用一个已知的未占用ID作为中介将其拆分为3个UPDATE,例如:99980-> -1,99982-> 99980,-1-> 99982。

An alternative approach with the same effect would be to update the non-key columns that differ between the two records: 具有相同效果的另一种方法是更新两个记录之间不同的非关键列:

UPDATE PERSON SET FIRST_NAME='Mary', Age=25 WHERE ID=99980
UPDATE PERSON SET FIRST_NAME='John', Age=45 WHERE ID=99982

Step 1.Reset Auto Increment property & Primary Key (Put them OFF) 步骤1.重置自动增量属性和主键(将其关闭)

Step 2.Run these update commands: 第2步。运行以下更新命令:

Update YourTableName SET  ID=99982 WHERE ID=99980

and

Update YourTableName SET  ID=99980 WHERE FIRST_NAME='Mary' AND ID=99982

Step 3.Set Auto Increment Property & Primary Key again (Turn them ON). 第3步。再次设置自动增量属性和主键(将它们打开)。

Done 完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM