重命名主键和外键的VALUES

时间:2013-11-09 09:45:13

标签: sql postgresql rename postgresql-8.3

这样有两个表:

CREATE TABLE rooms (rid CHAR PRIMARY KEY);
CREATE TABLE users (uid INT PRIMARY KEY, rid CHAR FOREIGN KEY REFERENCES rooms(rid))

目标是重命名像这样的删除键(值,而不是表或列):

BEGIN TRANSACTION;
UPDATE rooms
SET rid = "9"||SUBSTRING(rid, 2)
WHERE TEXT(rid) LIKE "5%";
UPDATE users
SET rid = "9"||SUBSTRING(rid, 2)
WHERE TEXT(rid) LIKE "5%";
END TRANSACTION;

当然,这会以外键约束错误结束。

在重命名的情况下调用“sp_rename”。但我以这种方式理解它只使用表和列,而不是值。

如何重命名外键约束的值?

已解决

BEGIN TRANSACTION;

ALTER TABLE users
DROP CONSTRAINT users_rid_fkey,
ADD FOREIGN KEY (rid) REFERENCES rooms(rid) ON UPDATE CASCADE ON DELETE RESTRICT;

UPDATE rooms
SET rid = '9'||SUBSTRING(rid, 2)
WHERE rid LIKE '5%';

END TRANSACTION;

1 个答案:

答案 0 :(得分:2)

你有几种方法......即:

  1. 删除约束,更新数据并重新添加约束。

  2. 更改约束,使其为on update cascade

  3. 更改约束以使其成为deferrable initially deferred

  4. 为房间添加一个正确的id列,并引用它,以完全避免这个问题。