我正在使用 Oracle 資料庫,并且我有這個生成Alter Table陳述句的查詢
(SELECT 'ALTER TABLE drop CONSTRAINT '
||constraint_name
||' ;'
FROM user_constraints
WHERE constraint_type = 'R'
AND table_name = 'PRINCIPALS_ROLES'
AND r_constraint_name =
(
SELECT constraint_name
FROM user_constraints
WHERE table_name = 'PRINCIPALS'
AND constraint_type= 'P' ))
當我運行此查詢時,我得到以下輸出。
ALTER TABLE drop CONSTRAINT PRINCIPAL_ID_FKEY ;
現在我想在生成這個查詢的同一個 sql 陳述句中運行上面的查詢。我們應該怎么做?我不想使用像 Declare --> Begin --> End 這樣的存盤程序。我希望我的查詢是單個可執行查詢。
uj5u.com熱心網友回復:
我不想使用像 Declare --> Begin --> End 這樣的存盤程序。我希望我的查詢是單個可執行查詢。
不幸的是,并非所有夢想都能實作。恐怕這是其中之一。因為,您所描述的是一個經典的動態 SQL 示例,它需要某種 PL/SQL;示例顯示了一個存盤程序,因此您可以只使用一條陳述句來運行它。
示例表:
SQL> create table principals (id number constraint pk_princ primary key);
Table created.
SQL> create table principals_roles
2 (id number constraint pk_princ_role primary key,
3 id_master number constraint fk_prole_princ references principals (id));
Table created.
虛擬程式;您可能希望重用它,因此您至少將表名作為引數傳遞。
SQL> create or replace procedure p_drop as
2 begin
3 for cur_r in (select
4 'ALTER TABLE ' || table_name || ' drop CONSTRAINT ' ||
5 constraint_name as command
6 from user_constraints
7 where constraint_type = 'R'
8 and table_name = 'PRINCIPALS_ROLES'
9 and r_constraint_name = (select constraint_name
10 from user_constraints
11 where table_name = 'PRINCIPALS'
12 and constraint_type = 'P'
13 )
14 ) loop
15 dbms_output.put_line(cur_r.command);
16 execute immediate cur_r.command;
17 end loop;
18 end;
19 /
Procedure created.
測驗:
SQL> set serveroutput on;
SQL> exec p_drop;
ALTER TABLE PRINCIPALS_ROLES drop CONSTRAINT FK_PROLE_PRINC
PL/SQL procedure successfully completed.
如果一切順利,principals_roles現在應該只有它的主鍵約束:
SQL> select constraint_name from user_constraints where table_name = 'PRINCIPALS_ROLES';
CONSTRAINT_NAME
--------------------------------------------------------------------------------
PK_PRINC_ROLE
SQL>
uj5u.com熱心網友回復:
你有一個 DDL 并且執行它需要動態執行立即,這不能在單個陳述句中完成。您將需要至少 2 個陳述句,并且立即執行需要一個BEGIN END塊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497752.html
