Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a subquery be used in an Oracle ALTER statement?

Given a table name and a column name, I'm trying to dynamically drop an Oracle constraint that I don't know the name of ahead of time.

I can find the constraint name with this query:

SELECT CONSTRAINT_NAME 
 FROM USER_CONS_COLUMNS 
 WHERE TABLE_NAME = 'MyTable' AND 
 COLUMN_NAME='MyColumn' AND POSITION IS NULL

My first thought was to use a subquery, but that doesn't work and results in an ORA-02250 error:

ALTER TABLE MyTable 
  DROP CONSTRAINT (
   SELECT CONSTRAINT_NAME 
    FROM USER_CONS_COLUMNS 
    WHERE TABLE_NAME = 'MyTable' AND 
    COLUMN_NAME='MyColumn' AND POSITION IS NULL)

So far, the only working solution I have is the following, but it feels unnecessarily complex:

DECLARE 
statement VARCHAR2(2000);
constr_name VARCHAR2(30);
BEGIN
  SELECT CONSTRAINT_NAME INTO constr_name 
   FROM USER_CONS_COLUMNS 
   WHERE table_name  = 'MyTable' AND 
   column_name = 'MyColumn' AND position is null;
   statement := 'ALTER TABLE MyTable DROP CONSTRAINT '|| constr_name;
   EXECUTE IMMEDIATE(statement); 
END;
/

Is there a way to do this with a subquery, as I originally intended? If not, can anyone suggest a more concise way to do this?

like image 490
Justin Garrick Avatar asked May 05 '11 20:05

Justin Garrick


People also ask

Can we use subquery in alter statement?

You cannot. SQL and DDL are basically two separated languages.

Which statement Cannot use a subquery?

You cannot include text, unitext, or image datatypes in subqueries. Subqueries cannot manipulate their results internally, that is, a subquery cannot include the order by clause, the compute clause, or the into keyword.

In which all clauses can a subquery be used?

A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT , INSERT , UPDATE , or DELETE statement, or inside another subquery.

Can you use a subquery in an in statement?

Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table.


1 Answers

You cannot. SQL and DDL are basically two separated languages. Your solution is correct.

like image 104
Horus Avatar answered Sep 16 '22 12:09

Horus