2013-11-09 68 views
0

有兩個表是這樣的:重命名VALUES

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; 

當然,這會以外鍵約束的錯誤結束。

在重命名oftn「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; 

回答

2

您已經幾種方法...即:

  1. 刪除約束,更新數據,並重新添加約束。

  2. 更改約束,使其爲on update cascade

  3. 更改約束條件使其成爲deferrable initially deferred

  4. 爲房間添加一個正確的ID列,並引用它來完全避免該問題。

+0

我帶了變種2.非常感謝! – Chickenmarkus