对于使用Oracle 8 DB的应用程序,我提供了一个SQL脚本来设置触发器,序列等内容,可以将其复制并粘贴到SQL * Plus中。如果我尝试创建的序列已存在,我希望脚本不会因错误而停止。对于触发器,可以使用“创建或替换触发器...”轻松完成,但对于序列,这不起作用。我也试过“”如果不存在mysequence然后创建序列...“但它也没有。还有其他选择吗?
或者,如果这是不可能的,有没有办法在没有SQL * Plus的情况下执行“drop sequence mysequence”,如果mysequence不存在则中止脚本?
答案 0 :(得分:15)
DECLARE
v_dummy NUMBER;
BEGIN
-- try to find sequence in data dictionary
SELECT 1
INTO v_dummy
FROM user_sequences
WHERE sequence_name = 'MY_SEQUENCE_NAME';
-- if sequence found, do nothing
EXCEPTION
WHEN no_data_found THEN
-- sequence not found, create it
EXECUTE IMMEDIATE 'create sequence my_sequence_name';
END;
答案 1 :(得分:8)
如果您确定该脚本将始终在SQL * Plus下运行,您可以使用指令对CREATE SEQUENCE语句进行括号以继续出错:
WHENEVER SQLERROR CONTINUE
-- create sequences here, ignoring errors
WHENEVER SQLERROR EXIT SQL.SQLCODE
请注意,如果创建序列语句中存在其他错误(权限问题,语法失败等),则会忽略它们
答案 2 :(得分:4)
我喜欢:
DECLARE
C NUMBER;
BEGIN
SELECT COUNT(*) INTO C
FROM ALL_TRIGGERS
WHERE OWNER = 'YOUROWNER'
AND TRIGGER_NAME = 'YOURTRIGGER';
IF (C = 0) THEN
EXECUTE IMMEDIATE '
CREATE TRIGGER "YOUROWNER"."YOURTRIGGER"
blah blah blah your trigger blah blah
';
END IF;
END;
/
答案 3 :(得分:1)
您可以检查user_sequence
表以查看正在创建的序列是否已存在。
与davek
的解决方案类似:
这个想法是,在创建任何序列之前,删除序列并创建它,全部在动态SQL中,创建一个函数,并说当你需要创建10个序列时,让函数小心......
function crt_seq(p_seq_name varchar2)
return boolean
begin
for i in (select 1 from user_sequence where sequence_name = upper(p_seq_name))
loop
---- Already exists. You can drop and recreate or return false to error out
execute immediate 'drop sequence '||p_seq_name;
execute immediate 'create sequence '||p_seq_name||' start with 1 increment
by 1 nocache';
end loop;
return true;
exception
when others then
return false;
end;
您可以参数化所有其他选项,并有一个精心设计的功能来为您创建序列。
答案 4 :(得分:0)
DECLARE
lsSeqName VARCHAR2(32 CHAR) := UPPER('MY_SEQUENCE_NAME');
lnSeqCount NUMBER;
BEGIN
-- try to find sequence in data dictionary
SELECT count(1)
INTO lnSeqCount
FROM user_sequences
WHERE UPPER(sequence_name) = lsSeqName;
-- if sequence not found, create it
IF lnSeqCount = 0 THEN
EXECUTE IMMEDIATE 'CREATE SEQUENCE ' || lsSeqName || ' START WITH 1 MINVALUE 1 MAXVALUE 1000000000000000 INCREMENT BY 1 NOCYCLE CACHE 20 NOORDER';
END IF;
END;
/
OR
-- helper method
PROCEDURE createSeqIfNotExists (
isSeqName VARCHAR2
) IS
lnSeqCount NUMBER;
BEGIN
-- try to find sequence in data dictionary
SELECT count(1)
INTO lnSeqCount
FROM user_sequences
WHERE UPPER(sequence_name) = UPPER(isSeqName);
-- if sequence not found, create it
IF lnSeqCount = 0 THEN
EXECUTE IMMEDIATE 'CREATE SEQUENCE ' || UPPER(isSeqName) || ' START WITH 1 MINVALUE 1 MAXVALUE 1000000000000000 INCREMENT BY 1 NOCYCLE CACHE 20 NOORDER';
END IF;
END createSeqIfNotExists;
-- call method
BEGIN
createSeqIfNotExists('MY_SEQUENCE_NAME');
END;
/