2017-06-16 34 views
1

我有這些拖車表:如何做多個插入到SQL表的外鍵關係安全地刪除第一次插入如果第二插入失敗

CREATE TABLE cities (
     city  varchar(80) primary key, 
     location point 
); 

CREATE TABLE weather (
     city  varchar(80) references cities(city), 
     temp_lo int, 
     temp_hi int, 
     prcp  real, 
     date  date 
); 

我把PostgreSQL Knex JavaScript的驅動

雖然做一個插入事務,我怎麼能確保如果我在插入表格城市後在插入表格天氣時出現錯誤,我可以返回並刪除表格城市中的插入以確保數據庫的完整性。 請讓我只需要一窺我能做些什麼。

+0

你正在使用什麼rdms? (mysql,oracel,mssql) – Arion

+0

*我如何插入確保刪除城市* ...這件作品沒有多大意義。你可以嘗試改說嗎? –

+0

你好,我編輯了問題鄉親 – Danstan

回答

-1

你可以寫AFTER INSERTtrigger ON weather表。 由於您的citycities表中的主鍵,當weather表中的插入失敗時,您可以使用刪除城市表中的條目,其中條件-city = NEW.city
NEW.city表示當前在天氣表中插入的城市的值,並且插入失敗。

+0

讓我試試這個。謝謝 – Danstan

+0

當然。如果這對你有用,請不要忘記加註並接受答案。 –

+0

當然@ Keyur Panchal – Danstan

1

也許我明白了問題的錯誤,但這聽起來像是使用事務的基本情況。只需啓動事務,執行插入操作,並且任何插入操作都將失敗回滾。隨着knex你可以做這樣的(http://knexjs.org/#Transactions):

knex.transaction(trx => { 
    return trx('cities') 
    .insert({ 
     city: 'inari', 
     ... rest of the fields ... 
    }) 
    .then(() => { 
    return trx('weather').insert({ 
     city: 'inari', 
     ... rest of the fields ... 
    }); 
    }); 
}) 
.then(() => { 
    console.log('inserted 2 rows'); 
}) 
.catch(err => { 
    console.log('one of the queries failed, no rows were inserted and transaction was rolled back') 
}); 

你不應該使用這個觸發器。

+0

這次它確實......一個人不應該使用觸發器來完成OP所描述的功能。對於初學程序員來說,他們可能認爲這是一個好主意,這顯然是誤導性的。 –