How can I edit the columns in an existing view - sql

I have a view with a typo:
CREATE OR REPLACE VIEW "USER"."VW_X" AS (
SELECT id,
name,
decode(WRONG_COLUMN, 1, 'T', 0, 'F') AS problem
FROM "USER"."TEST");
For some reason using
CREATE OR REPLACE VIEW "USER"."VW_X" AS (
SELECT id,
name,
decode(RIGHT_COLUMN, 1, 'T', 0, 'F') AS problem
FROM "USER"."TEST");
results in the following message:
Error starting at line : 5 in command -
CREATE OR REPLACE VIEW "USER"."VW_X" AS (
SELECT id,
name,
decode(RIGHT_COLUMN, 1, 'T', 0, 'F') AS problem
FROM "USER"."TEST")
Error report -
SQL Error: ORA-02449: unique/primary keys in table referenced by foreign keys
02449. 00000 - "unique/primary keys in table referenced by foreign keys"
*Cause: An attempt was made to drop a table with unique or
primary keys referenced by foreign keys in another table.
*Action: Before performing the above operations the table, drop the
foreign key constraints in other tables. You can see what
constraints are referencing a table by issuing the following
command:
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = "tabnam";
I didn't even know that a view was a valid target for a reference. So here's the problem:
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = "USER"."VW_X";
returns nothing, this:
SELECT a.table_name,
a.column_name,
a.constraint_name,
c.owner,
c.r_owner,
c_pk.table_name r_table_name,
c_pk.constraint_name r_pk,
c.status
FROM all_cons_columns a
JOIN all_constraints c
ON a.owner = c.owner AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk
ON c.r_owner = c_pk.owner AND c.r_constraint_name = c_pk.constraint_name
WHERE c_pk.table_name = 'VW_X' or c.table_name = 'VW_X';
(a variant on the top answer to this post)
returns four constraints all of which with a status of 'DISABLED'.
I have looked into ALTER VIEW (the name sounded pretty promising), but it does not appear to be what I'm looking for.
Any suggestions?
NOTE: It is possible probable that there are some syntax errors in the provided sample code. These are mockups, in the interest of simplicity and out of professional paranoia, about a dozen irrelevant columns have been removed and names have been altered.
EDIT:
this is Oracle11g
EDIT:
The solution I found was
-- drop view.
DROP VIEW "USER"."VW_X" CASCADE CONSTRAINTS;
commit;
-- create view.
CREATE OR REPLACE VIEW "USER"."VW_X" AS (
SELECT id,
name,
decode(RIGHT_COLUMN, 1, 'T', 0, 'F') AS problem
FROM "USER"."TEST");
commit;
CASCADE CONSTRAINTS appears to be the missing link. I am pretty sure the constraints are lost, but I don't particularly care.

ALTER VIEW
AS
SELECT
[new column name] = wrongcolumn

Here is a solution that would drop the FK, create the view, then recreate the FK
-- create view with unique constraint
create or replace view v_foo
(id unique disable novalidate, val)
as
select id, val from foo;
-- create second view
create or replace view v_bar
(id, val)
as
(select id, val from bar);
-- add FK to second view
alter view v_bar
add constraint v_bar_ref
foreign key (id) references v_foo(id)
disable novalidate;
-- add a column, this fails b/c of FK constraint
create or replace view v_foo
(id unique disable novalidate, val, dummy)
as
select id, val, 1 from foo;
-- remove constraint
alter view v_bar
drop constraint v_bar_ref;
-- make changes to view
create or replace view v_foo
(id unique disable novalidate, val, dummy)
as
select id, val, 1 from foo;
-- recreate FK constraint
alter view v_bar
add constraint v_bar_ref
foreign key (id) references v_foo(id)
disable novalidate;

Related

Can I alter the constraints of one table by using the constraints of another table?

I had to drop a table and remake it using an archive. In the process, I lost the table's constraints--things like the primary key--triggers, indices, and more. I have, however, the same table on a different DB, which has all the appropriate constraints.
I have tried adding the constraints, triggers, and indices manually, but there are just too many.
I was wondering if I could do something like:
alter table t73
modify col_n....col_n+1
using (select constraints from t73#otherdb)
No, that won't work.
What you could do is to use some GUI (like TOAD or SQL Developer), find table t73, have a look at its Script which contains all commands (CREATE TABLE, CREATE INDEX, CREATE CONSTRAINT, ...) and copy/paste the ones you need and execute them in your current database.
That would be quick.
If you want to do it right (you know, pretending you know what you're doing, just like I do), then see DBMS_METADATA.GET_DDL and extract those commands from the database.
The final result should be the same.
this is below example how you can use dbms_metadata.get_ddl oracle package
create table EX_EMPLOYEe ( id number(5) null, name varchar2(100))
/
alter table ex_Employee add constraint PK_EX_EMPLOYEE primary key (id)
/
alter table ex_Employee add constraint FK_EX_EMPLOYEE foreign key (id)
references ex_Employee1 (id)
/
create table EX_EMPLOYEe1 ( id number(5) null, name varchar2(100))
/
alter table ex_Employee1 add constraint PK_EX_EMPLOYEE1 primary key (id)
alter table SYS_PARAM_KEY_LABEL
add constraint FK1_SYS_PARAM_KEY_LABEL foreign key (KEY_GROUP_ID)
references SYS_PARAM_KEY_GROUP (KEY_GROUP_ID);
/
CREATE INDEX IDX_EX_EMPLOYEe on ex_employee(name)
/
Create or replace PROCEDURE P_EX_EMPLOYEe as
begin
select id from ex_employee where rownum=1;
end;
/
CREATE OR REPLACE TRIGGER TRG_EX_EMPLOYEe AFTER DELETE ON EX_EMPLOYEe
FOR EACH ROW
BEGIN
DELETE FROM ex_employee1 WHERE id = :OLD.ID;
END;
/
select to_char( dbms_metadata.get_ddl('CONSTRAINT', c.constraint_name)) from user_constraints c where table_name='EX_EMPLOYEE'
and c.constraint_type='P'
union
select to_char( dbms_metadata.get_ddl('REF_CONSTRAINT', c.constraint_name)) from user_constraints c where table_name='EX_EMPLOYEE'
and c.constraint_type='R'
union
select to_char( dbms_metadata.get_ddl('INDEX', c.index_name)) from user_indexes c where table_name='EX_EMPLOYEE'
union
select to_char( dbms_metadata.get_ddl('PROCEDURE', d.name)) from user_dependencies d where d.referenced_name='EX_EMPLOYEE'
and d.type='PROCEDURE'
union
select to_char( dbms_metadata.get_ddl('TRIGGER', d.name)) from user_dependencies d where d.referenced_name='EX_EMPLOYEE'
and d.type='TRIGGER'

DROPPING FOREIGN KEY BY CONSTNAME

I want to drop a foreign key from a table but I do not know its identifier.
I get the identifier from the SYSCAT.KEYCOLUSE table.
After that I try to use that identifier to drop the FK.
Getting identifier
SELECT keycoluse.CONSTNAME FROM SYSCAT.KEYCOLUSE keycoluse WHERE TABSCHEMA = 'USER1' AND TABNAME = 'TABLE1' AND COLNAME = 'ID_TABLE'
result = ID000000001
Dropping FK
ALTER TABLE TABLE1
DROP FOREIGN KEY (SELECT keycoluse.CONSTNAME FROM SYSCAT.KEYCOLUSE keycoluse WHERE TABSCHEMA = 'USER1' AND TABNAME = 'TABLE1' AND COLNAME = 'ID_TABLE');
this throw error: [Error Code: -104, SQL State: 42601]
But if I use the identifier I got before in this way, it works:
ALTER TABLE TABLE1
DROP FOREIGN KEY ID000000001;
In this way, it does not work:
ALTER TABLE TABLE1
DROP FOREIGN KEY 'ID000000001';
When I execute the SELECT to get the id, it gets a varchar 'ID000000001' and that gives the error.
¿Is there a way to cast the result of the SELECT into the same type that we have in this command?
ALTER TABLE TABLE1
DROP FOREIGN KEY ID000000001;
You cannot use a variable (returned by a subselect) or a literal where an identifier is required.
What you can do is generate a script from the query you have, although I cannot imagine why you would want to use such a complex approach to drop a single constraint:
SELECT
'ALTER TABLE', 'TABLE1',
'DROP FOREIGN KEY', keycoluse.CONSTNAME
FROM
SYSCAT.KEYCOLUSE keycoluse
WHERE
TABSCHEMA = 'USER1' AND TABNAME = 'TABLE1' AND COLNAME = 'ID_TABLE'
The query will return a correct ALTER statement. You can copy/paste it into your favourite client software or write results to a text file and execute it, for example, with
db2 -f mydropscript.sql

Generate SQL to update primary key

I want to change a primary key and all table rows which reference to this value.
# table master
master_id|name
===============
foo|bar
# table detail
detail_id|master_id|name
========================
1234|foo|blu
If I give a script or function
table=master, value-old=foo, value-new=abc
I want to create a SQL snippet that executes updates on all tables which refere to table "master":
update detail set master_id=value-new where master_id=value-new;
.....
With the help of introspection, this should be possible.
I use postgres.
Update
The problem is, that there are many tables which have a foreign-key to the table "master". I want a way to automatically update all tables which have a foreign-key to master table.
The easiest way to deal with primary key changes - by far - is to ALTER your referring foreign key constraints to be ON UPDATE CASCADE.
You are then free to update the primary key values, and the changes will cascade to child tables. It can be a very slow process due to all the random I/O, but it will work.
You do need to watch out not to violate uniqueness constraints on the primary key column during the process.
A fiddlier but faster way is to add a new UNIQUE column for the new PK, populate it, add new columns to all the referring tables that point to the new PK, drop the old FK constraints and columns, then finally drop the old PK.
If you need to change PK you could use DEFFERED CONSTRAINTS:
SET CONSTRAINTS sets the behavior of constraint checking within the current transaction. IMMEDIATE constraints are checked at the end of each statement. DEFERRED constraints are not checked until transaction commit. Each constraint has its own IMMEDIATE or DEFERRED mode.
Data preparation:
CREATE TABLE master(master_id VARCHAR(10) PRIMARY KEY, name VARCHAR(10));
INSERT INTO master(master_id, name) VALUES ('foo', 'bar');
CREATE TABLE detail(detail_id INT PRIMARY KEY, master_id VARCHAR(10)
,name VARCHAR(10)
,CONSTRAINT fk_det_mas FOREIGN KEY (master_id) REFERENCES master(master_id));
INSERT INTO detail(detail_id, master_id, name) VALUES (1234,'foo','blu');
In normal situtation if you try to change master detail you will end up with error:
update detail set master_id='foo2' where master_id='foo';
-- ERROR: insert or update on table "detail" violates foreign key
-- constraint "fk_det_mas"
-- DETAIL: Key (master_id)=(foo2) is not present in table "master"
update master set master_id='foo2' where master_id='foo';
-- ERROR: update or delete on table "master" violates foreign key
-- constraint "fk_det_mas" on table "detail"
-- DETAIL: Key (master_id)=(foo) is still referenced from table "detail".
But if you change FK resolution to deffered, there is no problem:
ALTER TABLE detail DROP CONSTRAINT fk_det_mas ;
ALTER TABLE detail ADD CONSTRAINT fk_det_mas FOREIGN KEY (master_id)
REFERENCES master(master_id) DEFERRABLE;
BEGIN TRANSACTION;
SET CONSTRAINTS ALL DEFERRED;
UPDATE master set master_id='foo2' where master_id = 'foo';
UPDATE detail set master_id='foo2' where master_id = 'foo';
COMMIT;
DBFiddle Demo
Please note that you could do many things inside transaction, but during COMMIT all referential integrity checks have to hold.
EDIT
If you want to automate this process you could use dynamic SQL and metadata tables. Here Proof of Concept for one FK column:
CREATE TABLE master(master_id VARCHAR(10) PRIMARY KEY, name VARCHAR(10));
INSERT INTO master(master_id, name)
VALUES ('foo', 'bar');
CREATE TABLE detail(detail_id INT PRIMARY KEY, master_id VARCHAR(10),
name VARCHAR(10)
,CONSTRAINT fk_det_mas FOREIGN KEY (master_id)
REFERENCES master(master_id)DEFERRABLE ) ;
INSERT INTO detail(detail_id, master_id, name) VALUES (1234,'foo','blu');
CREATE TABLE detail_second(detail_id INT PRIMARY KEY, name VARCHAR(10),
master_id_second_name VARCHAR(10)
,CONSTRAINT fk_det_mas_2 FOREIGN KEY (master_id_second_name)
REFERENCES master(master_id)DEFERRABLE ) ;
INSERT INTO detail_second(detail_id, master_id_second_name, name)
VALUES (1234,'foo','blu');
And code:
BEGIN TRANSACTION;
SET CONSTRAINTS ALL DEFERRED;
DO $$
DECLARE
old_pk TEXT = 'foo';
new_pk TEXT = 'foo2';
table_name TEXT = 'master';
BEGIN
-- update childs
EXECUTE (select
string_agg(FORMAT('UPDATE %s SET %s = ''%s'' WHERE %s =''%s'' ;'
,c.relname,pa.attname, new_pk,pa.attname, old_pk),CHR(13)) AS sql
from pg_constraint pc
join pg_class c on pc.conrelid = c.oid
join pg_attribute pa ON pc.conkey[1] = pa.attnum
and pa.attrelid = pc.conrelid
join pg_attribute pa2 ON pc.confkey[1] = pa2.attnum
and pa2.attrelid = table_name::regclass
where pc.contype = 'f');
-- update parent
EXECUTE ( SELECT FORMAT('UPDATE %s SET %s = ''%s'' WHERE %s =''%s'';'
,c.relname,pa.attname, new_pk,pa.attname, old_pk)
FROM pg_constraint pc
join pg_class c on pc.conrelid = c.oid
join pg_attribute pa ON pc.conkey[1] = pa.attnum
and pa.attrelid = pc.conrelid
WHERE pc.contype IN ('p','u')
AND conrelid = table_name::regclass
);
END
$$;
COMMIT;
DBFiddle Demo 2
EDIT 2:
I tried it, but it does not work. It would be nice, if the script could show the SQL. This is enough. After looking at the generated SQL I can execute it if psql -f
have you tried it? It did not work for me.
Yes, I have tried it. Just check above live demo links.
I prepare the same demo with more debug info:
values before
executed SQL
values after
Please make sure that FKs are defined as DEFFERED.
DBFiddle 2 with debug info
LAST EDIT
Then I wanted to see the sql instead of executing it. I removed "perform" from your fiddle, but then I get an error. See: http://dbfiddle.uk/?rdbms=postgres_10&fiddle=b9431c8608e54b4c42b5dbd145aa1458
If you only want to get SQL code you could create function:
CREATE FUNCTION generate_update_sql(table_name VARCHAR(100), old_pk VARCHAR(100), new_pk VARCHAR(100))
RETURNS TEXT
AS
$$
BEGIN
RETURN
-- update childs
(SELECT
string_agg(FORMAT('UPDATE %s SET %s = ''%s'' WHERE %s =''%s'' ;', c.relname,pa.attname, new_pk,pa.attname, old_pk),CHR(13)) AS sql
FROM pg_constraint pc
JOIN pg_class c on pc.conrelid = c.oid
JOIN pg_attribute pa ON pc.conkey[1] = pa.attnum and pa.attrelid = pc.conrelid
JOIN pg_attribute pa2 ON pc.confkey[1] = pa2.attnum and pa2.attrelid = table_name::regclass
WHERE pc.contype = 'f') || CHR(13) ||
-- update parent
(SELECT FORMAT('UPDATE %s SET %s = ''%s'' WHERE %s =''%s'';', c.relname,pa.attname, new_pk,pa.attname, old_pk)
FROM pg_constraint pc
JOIN pg_class c on pc.conrelid = c.oid
JOIN pg_attribute pa ON pc.conkey[1] = pa.attnum and pa.attrelid = pc.conrelid
WHERE pc.contype IN ('p','u')
AND conrelid = table_name::regclass)
;
END
$$ LANGUAGE plpgsql;
And execution:
SELECT generate_update_sql('master', 'foo', 'foo');
UPDATE detail SET master_id = 'foo' WHERE master_id ='foo' ;
UPDATE detail_second SET master_id_second_name = 'foo'
WHERE master_id_second_name ='foo' ;
UPDATE master SET master_id = 'foo' WHERE master_id ='foo';
DBFiddle Function Demo
Of course there is a place for improvement for example handling identifiers like "table with space in name" and so on.
I found a dirty solution: in psql the command \d master_table show the relevant information. With some text magic, it is possible to extract the needed information:
echo "UPDATE master_table SET id='NEW' WHERE id='OLD';" > tmp/foreign-keys.txt
psql -c '\d master_table' | grep -P 'TABLE.*CONSTRAINT.*FOREIGN KEY' \
>> tmp/foreign-keys.txt
reprec '.*TABLE ("[^"]*") CONSTRAINT[^(]*\(([^)]*)\).*' \
"UPDATE \1 set \2='NEW' WHERE \2='OLD';" \
tmp/foreign-keys.txt
psql -1 -f tmp/foreign-keys.txt
Result:
UPDATE "master_table" SET id='NEW' WHERE id='OLD';
UPDATE "other_table" SET master_id='NEW' WHERE master_id='OLD';
...
But better solutions are welcome.
I dont think you can update the Primary key. One possible work around is that you can remove the primary key constraint from the table column. Then update the column value.
Updating the primary key can lead you to some serious problems. But if you still want to do it.
Please refer this Thread.(kevchadders has given a solution.)

Postgres: Add constraint if it doesn't already exist

Does Postgres have any way to say ALTER TABLE foo ADD CONSTRAINT bar ... which will just ignore the command if the constraint already exists, so that it doesn't raise an error?
A possible solution is to simply use DROP IF EXISTS before creating the new constraint.
ALTER TABLE foo DROP CONSTRAINT IF EXISTS bar;
ALTER TABLE foo ADD CONSTRAINT bar ...;
Seems easier than trying to query information_schema or catalogs, but might be slow on huge tables since it always recreates the constraint.
Edit 2015-07-13:
Kev pointed out in his answer that my solution creates a short window when the constraint doesn't exist and is not being enforced. While this is true, you can avoid such a window quite easily by wrapping both statements in a transaction.
This might help, although it may be a bit of a dirty hack:
create or replace function create_constraint_if_not_exists (
t_name text, c_name text, constraint_sql text
)
returns void AS
$$
begin
-- Look for our constraint
if not exists (select constraint_name
from information_schema.constraint_column_usage
where table_name = t_name and constraint_name = c_name) then
execute constraint_sql;
end if;
end;
$$ language 'plpgsql'
Then call with:
SELECT create_constraint_if_not_exists(
'foo',
'bar',
'ALTER TABLE foo ADD CONSTRAINT bar CHECK (foobies < 100);')
Updated:
As per Webmut's answer below suggesting:
ALTER TABLE foo DROP CONSTRAINT IF EXISTS bar;
ALTER TABLE foo ADD CONSTRAINT bar ...;
That's probably fine in your development database, or where you know you can shut out the apps that depend on this database for a maintenance window.
But if this is a lively mission critical 24x7 production environment you don't really want to be dropping constraints willy nilly like this. Even for a few milliseconds there's a short window where you're no longer enforcing your constraint which may allow errant values to slip through. That may have unintended consequences leading to considerable business costs at some point down the road.
You can use an exception handler inside an anonymous DO block to catch the duplicate object error.
DO $$
BEGIN
BEGIN
ALTER TABLE foo ADD CONSTRAINT bar ... ;
EXCEPTION
WHEN duplicate_table THEN -- postgres raises duplicate_table at surprising times. Ex.: for UNIQUE constraints.
WHEN duplicate_object THEN
RAISE NOTICE 'Table constraint foo.bar already exists';
END;
END $$;
http://www.postgresql.org/docs/9.4/static/sql-do.html http://www.postgresql.org/docs/9.4/static/plpgsql-control-structures.html
http://www.postgresql.org/docs/9.4/static/errcodes-appendix.html
you can run query over pg_constraint table to find constraint exists or not.like:
SELECT 1 FROM pg_constraint WHERE conname = 'constraint_name'"
Creating constraints can be an expensive operation on a table containing lots of data so I recommend not dropping constraints only to immediately create them again immediately after - you only want to create that thing once.
I chose to solve this using an anonymous code block, very similar to Mike Stankavich, however unlike Mike (who catches an error) I first check to see if the constraint exists:
DO $$
BEGIN
IF NOT EXISTS ( SELECT constraint_schema
, constraint_name
FROM information_schema.check_constraints
WHERE constraint_schema = 'myschema'
AND constraint_name = 'myconstraintname'
)
THEN
ALTER TABLE myschema.mytable ADD CONSTRAINT myconstraintname CHECK (column <= 100);
END IF;
END$$;
Using information_schema.constraint_column_usage to check for the constraint doesn't work for foreign keys. I use pg_constraint to check for primary keys, foreign keys or unique constraints:
CREATE OR REPLACE FUNCTION add_constraint(t_name text, c_name text, constraint_sql text)
RETURNS void
AS $$
BEGIN
IF NOT EXISTS(
SELECT c.conname
FROM pg_constraint AS c
INNER JOIN pg_class AS t ON c.conrelid = t."oid"
WHERE t.relname = t_name AND c.conname = c_name
) THEN
EXECUTE 'ALTER TABLE ' || t_name || ' ADD CONSTRAINT ' || c_name || ' ' || constraint_sql;
END IF;
END;
$$
LANGUAGE plpgsql;
Examples:
SELECT add_constraint('client_grant_system_scopes', 'client_grant_system_scopes_pk', 'PRIMARY KEY (client_grants_id, tenant, "scope");');
SELECT add_constraint('client_grant_system_scopes', 'client_grant_system_scopes_fk', 'FOREIGN KEY (tenant,"scope") REFERENCES system_scope(tenant,"scope") ON DELETE CASCADE;');
SELECT add_constraint('jwt_assertion_issuers', 'jwt_assertion_issuers_issuer_key', 'UNIQUE (issuer);');
Take advantage of regclass to reduce verbosity, increase performance, and avoid errors related to table naming clashes between schemas:
DO $$ BEGIN
IF NOT EXISTS (SELECT FROM pg_constraint
WHERE conrelid = 'foo'::regclass AND conname = 'bar') THEN
ALTER TABLE foo ADD CONSTRAINT bar...;
END IF;
END $$;
This will also work for tables in other schemas, e.g.:
DO $$ BEGIN
IF NOT EXISTS (SELECT FROM pg_constraint
WHERE conrelid = 's.foo'::regclass AND conname = 'bar') THEN
ALTER TABLE s.foo ADD CONSTRAINT bar...;
END IF;
END $$;
In psql You can use metacommand \gexec for run generated query.
SELECT 'ALTER TABLE xx ADD CONSTRAINT abc' WHERE not EXISTS (SELECT True FROM pg_constraint WHERE conname = 'abc') \gexec
For me those solutions didn't work because the constraint was a primary key.
This one worked for me:
ALTER TABLE <table.name> DROP CONSTRAINT IF EXISTS <constraint.name> CASCADE;
Considering all the above mentioned answers , the below approach help if you just want to check if a constraint exist in the table in which you are trying to insert and raise a notice if there happens to be one
DO
$$ BEGIN
IF NOT EXISTS (select constraint_name
from information_schema.table_constraints
where table_schema='schame_name' and upper(table_name) =
upper('table_name') and upper(constraint_name) = upper('constraint_name'))
THEN
ALTER TABLE TABLE_NAME ADD CONSTRAINT CONTRAINT_NAME..... ;
ELSE raise NOTICE 'Constraint CONTRAINT_NAME already exists in Table TABLE_NAME';
END IF;
END
$$;
Don't know why so many lines of code ?
-- SELECT "Column1", "Column2", "Column3" , count(star) FROM dbo."MyTable" GROUP BY "Column1" , "Column2" , "Column3" HAVING count(*) > 1;
alter table dbo."MyTable" drop constraint if exists "MyConstraint_Name" ;
ALTER TABLE dbo."MyTable" ADD CONSTRAINT "MyConstraint_Name" UNIQUE("Column1", "Column3", "Column2");

Displaying the constraints in a table

Hello I am trying to display the constraints in one of my tables but for some reason I get the message no rows selected. Noted below is the table I have created.
Create table Teams (
TeamID varCHAR2(4) constraint Teams_TeamID_PK Primary Key,
TeamName VARCHAR2(40)
);
This is the code I am using to show my constraints.
SELECT constraint_name,
constraint_type,
search_condition
FROM USER_CONSTRAINTS
WHERE table_name = 'Teams';
I am a rookie so I want to make sure I understand what is wrong. I have tried to drop the table thinking that my constraints did not take - I did not, nor did I receive any errors when I created the table and I am referencing TeamID in another table. So when I try to drop the table I get an error message when is what I was hoping for.
Try this:
SELECT constraint_name,
constraint_type,
search_condition
FROM USER_CONSTRAINTS
WHERE table_name = 'TEAMS';
Unless double-quoted when created, all object names in Oracle are upper case.
I personally use:
SELECT * FROM all_constraints WHERE Table_Name = <TableName>;
Use the following code:
show create table table_name;
select dbms_mview.get_ddl('TABLE',USER,'TEAMS') from dual;
If you prefer the CamelCase names, your create table script should have been:
Create table "Teams" (
"TeamID" varCHAR2(4) constraint "Teams_TeamID_PK" Primary Key,
"TeamName" VARCHAR2(40)
);
Without double-quotes Oracle helpfully converts all identifiers to uppercase :)
Type the table name in upper case in where clause within the single quotes.
e.g. WHERE table_name = 'TEAMS';