2013-01-20 33 views
1

我有插入城市名稱的程序(並且還創建下一個id)。如果名稱已經存在,如何不插入城市名稱到表格?謝謝! 有我的代碼:程序 - 僅在不存在時插入

create or replace 
PROCEDURE PlaceName(
      town IN City.Name%TYPE) 
AS 
    id_C City.Id_City%TYPE; 
BEGIN 
    SELECT NVL(Max(c.Id_City)+1,1) INTO id_C 
    FROM City c; 
    INSERT INTO City 
    VALUES(id_C, town); 
End; 

回答

2

不,只有在不存在時才插入。這需要兩個操作。你必須檢查它是否存在,然後你必須插入記錄。

正確的方法是在桌面上創建unique constraint

ALTER TABLE table_name 
add CONSTRAINT constraint_name UNIQUE (city); 

你再搭上插入一個已經存在的城市時引發的異常,然後做任何你:如文檔中,或者如果你的表已經存在,你可以改變它添加約束規定你可以做到這一點在線希望獲得的信息。

您也錯誤地增加了您的ID。您應該使用SEQUENCE,這可以爲您節省另一個SELECT。

CREATE SEQUENCE city_seq 
    START WITH <current max ID> 
    INCREMENT BY 1; 

你的過程就變成了:

create or replace procedure PlaceName (
      town in city.name%type) is 

begin 
    insert into city 
    values(city_seq.nextval, town); 

-- Catch the raised exception if the city already exists. 
exception when dup_val_on_index then 
    <do something>; 
end; 
4

我和Ben同意,應該有一個UNIQUE約束的表(假定這是一個有效的約束),但可以用做簡單得多MERGE聲明:

MERGE INTO city c 
USING (SELECT 1 FROM dual) 
    ON c.name = town 
WHEN NOT MATCHED THEN INSERT (id, name) 
     VALUES (my_sequence.NEXTVAL, town); 

是不是真的在這裏所需要的USING條款,但它是強制性的MERGE語句。

0
insert into City 
    select seq.nextval, town 
from dual where not exists (select 1 from City where name = town); 

我嚴格推薦使用人工按鍵序列。 「select nvl(max())」非常糟糕。 如果您需要解釋,請問我:)