Dropping a table in Oracle SQL - sql

Whenever I try to drop a table or create a table it is showing these errors:
DROP TABLE SUBURB;
DROP TABLE STOCKITEM;
DROP TABLE MANUFACTURER;
DROP TABLE WAREHOUSE;
DROP TABLE CITY;
DROP TABLE STATE;
Error at line 1: ORA-02449: unique/primary keys in table referenced
by foreign keys
CREATE TABLE STATE (
statecode varchar(3)
,statename varchar(30)
,population number(8)
,primary key(statecode)
);
Error at line 1: ORA-00955: name is already used by an existing object
Can anybody explain why this happens?

If you're really sure you want to drop the table even though it's referenced in foreign keys you can force it like this:
drop table state cascade constraints;
This syntax is defined in the Oracle SQL Reference.
Note that this drops any foreign key relationships. So you will need to recreate them after you have rebuilt the table (and its primary key). Normally this is okay because the most common use case is trashing and re-creating schemas in Development or CI environments.
We can use cascade constraints to make our build scripts easier to maintain. There are two alternatives:
Explicitly drop the foreign key constraints before dropping the
tables, either with a script or with dynamic SQL.
Order the DROP
TABLE statements so that dependent tables are zapped first, along
with their pesky foreign keys. Easy enough for a handful of tables,
more painful with a large schema.

You can use below query to fetch the references of table which should be dropped before dropping the table.
select table_name, constraint_name, status, owner
from dba_constraints
where 1=1
--and r_owner = :p_owner --if you know schema
and constraint_type = 'R'
and r_constraint_name in
(
select constraint_name from dba_constraints
where constraint_type in ('P','U')
and lower(table_name) = lower(:p_table_name)
--and r_owner = :p_owner
)
order by table_name, constraint_name

if you create the primary key and also create the foreign key than you cannot drop the table
you drop the table in this way for example if you have the table of students or teachers you want to drop this table you should write
DROP TABLE students CASCADE CONSTRAINTS;
and also you drop the table of teachers
DROP TABLE teachers CASCADE CONSTRAINTS;

SUBURB
Table is a parent table for any other table First you drop the child table then you can drop the SUBURB table....
And a table named as STATE is already present in your database...so you cant create the table having the same name....once if you drop the STATE table you can create another....

here's the solution that works for me fine in Oracle sample database :
DROP TABLE ['Your_Table_Name'] STATE CASCADE CONSTRAINTS;

Related

Why Alter Table Primary key is not possible - Crate DB [duplicate]

I want to alter a table in my Crate DB to change the primary key constraint to add a column to the existing one. If I need to drop the constraint and create a new one what would be the SQL syntax for the same. I have been trying the conventional SQL syntax and it does not seem to work:
alter table my_data_table drop primary key;
the above command gives an error:
SQLActionException[SQLParseException: line 1:34: no viable alternative at input 'alter table my_data_table drop']
I checked the Alter table SQL reference and can only find ways to add columns but nothing about altering the constraints.So if you are aware of how to do this, please let me know. cheers!
there's no way to alter the primary key once a table has been created. You need to create a new table that has the schema you'd like to have and then either move the data over with COPY TO and COPY FROM or with insert into to_table (i) (select ... from t). With CrateDB > 2.0 it's also possible to rename tables, so you can still use the original table name.
First use the following code snippets for finding the constraints
SELECT Col.Column_Name from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col WHERE
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
AND Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = '<your table name>'
Then use this to drop the constraint
ALTER TABLE Customer DROP CONSTRAINT Constraint_Name;
P.S: considering you are using SQL SERVER

SQL Server Change Primary Key Data Type

I am working on SQL Server 2012:
I have a table with a primary key column as INT. I need to change this to a GUID.
Do I alter the table and remove int column as primary key?
Add the GUID column and set it as Primary and drop the old INT column?
Thank you.
You can't change primary key column,unless you drop it..Any operations to change its data type will lead to below error..
The object 'XXXX' is dependent on column 'XXXX'.
Only option is to
1.Drop primary key
2.change data type
3.recreate primary key
ALTER TABLE t1
DROP CONSTRAINT PK__t1__3213E83F88CF144D;
GO
alter table t1
alter column id varchar(10) not null
alter table t1 add primary key (id)
From 2012,there is a clause called (DROP_EXISTING = ON) which makes things simple ,by dropping the clustered index at final stage and also keeping old index available for all operations..But in your case,this clause won't work..
So i recommend
1.create new table with desired schema and indexes,with different name
2.insert data from old table to new table
3.finally at the time of switch ,insert data that got accumulated
4.Rename the table to old table name
This way you might have less downtime
You can change the date type of the primary key in three steps
Step 1 :- Drop the constraint associated with the Primary key
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Step 2 :- Alter the Primay key column to a valid primary key data type
ALTER TABLE table_name
ALTER COLUMN pk_column_name target_data_type(size) not null;
Step 3 :- Make the altered column primary key again
ALTER TABLE table_name
ADD PRIMARY KEY (pk_column_name);
PS :-
You can get the Constraint name from the error message when you try to alter the
pk_column
If you already have data in the pk_column make sure the source and target data type of the column both can be used for the existing data. else another two steps would be needed to move the existing data to a temporary column and then perform the steps and bring back that data after vetting and dropping that temporary column.
Below is a script I wrote to help us deploy a change to primary key column data type.
This script assumes there aren't any non-primary key constraints (e.g. foreign keys) depending on this column.
It has a few safety checks as this was designed to be deployed to different servers (dev, uat, live) without creating side effects if the table was somehow different on a server.
I hope this helps someone. Please let me know if you find anything wrong before down-voting. I'm more than happy to update the script.
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS C WITH (NOLOCK) WHERE C.TABLE_CATALOG = '<<DB>>' AND C.TABLE_SCHEMA = 'dbo' AND C.TABLE_NAME = '<<Table>>'
AND C.COLUMN_NAME = '<<COLUMN>>' AND C.DATA_TYPE = 'int') -- <- Additional test to check the current datatype so this won't make unnecessary or wrong updates
BEGIN
DECLARE #pkName VARCHAR(200);
SELECT #pkName = pkRef.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pkRef WITH (NOLOCK)
WHERE pkRef.TABLE_CATALOG = '<<DB>>' AND pkRef.TABLE_SCHEMA = 'dbo' AND TABLE_NAME = '<<Table>>'
IF(#pkName IS NOT NULL)
BEGIN
-- Make sure the primary key name is the one you are going to use in script beyond this point.
IF(#pkName != '<<PRIMARY KEY NAME>>')
BEGIN
RAISERROR ('Unexpected primary key name - The primary key found has a different name than expected. Please update the script.', 16, 1);
RETURN;
END
ALTER TABLE dbo.<<Table>>
DROP CONSTRAINT <<PRIMARY KEY NAME>>; -- Note: this is not a string or a variable (just type the PK name)
SELECT 'Dropped existing primary key';
END
ALTER TABLE dbo.<<Table>> ALTER COLUMN ID BIGINT
SELECT 'Updated column type to big int';
ALTER TABLE dbo.<<Table>>
ADD CONSTRAINT <<PRIMARY KEY NAME>> PRIMARY KEY CLUSTERED (<<COLUMN>>);
SELECT 'Created the primary key';
END
ELSE
BEGIN
SELECT 'No change required.';
END
In case other tables reference your PK with indexed FK's, these are the steps you must follow.
In this example, the main table's called Main, the single referencing table Reference. I'm changing the datatype to NVARCHAR(7). To use it:
Find/replace all these table names with your own;
Modify the data type;
You might also need to separately find/replace the dbo schema;
I'm using syntax which includes constraint names - if you want, also update these to your preferred naming conventions.
ALTER TABLE dbo.Main ADD IdNew NVARCHAR(7);
UPDATE dbo.Main SET IdNew = Id;
-- For all tables with FK's to this Main:
ALTER TABLE dbo.Reference ADD MainIdNew NVARCHAR(7);
UPDATE dbo.Reference SET MainIdNew = MainId;
ALTER TABLE dbo.Reference DROP CONSTRAINT FK_Reference_MainId_Main_Id;
DROP INDEX IX_Reference_MainId ON dbo.Reference;
ALTER TABLE dbo.Reference DROP COLUMN MainId;
-- Until here
ALTER TABLE dbo.Main DROP CONSTRAINT PK_Main;
ALTER TABLE dbo.Main DROP COLUMN Id;
EXEC sp_rename 'dbo.Main.IdNew', 'Id', 'COLUMN';
ALTER TABLE dbo.Main ALTER COLUMN Id NVARCHAR(7) NOT NULL;
ALTER TABLE dbo.Main ADD CONSTRAINT PK_Main PRIMARY KEY (Id);
-- Again for all tables with FK's to this Main:
EXEC sp_rename 'dbo.Reference.MainIdNew', 'MainId', 'COLUMN';
ALTER TABLE dbo.Reference ADD CONSTRAINT FK_Reference_MainId_Main_Id FOREIGN KEY (MainId) REFERENCES dbo.Main(Id);
CREATE INDEX IX_Reference_MainId ON dbo.Reference(MainId);
Right in the table you want to change the PK type >> Modify. Go in the column, change the type and save. If you want to see the code for such a change, before saving, you can right-click >> "Generate Change Script ..".
Using Microsoft SQL Server Management Studio do the following:
Open table Design
Change the primary key column type or any other change which is also possible with this way
Right click on the design area and select Generate Change Script
Accept Validation Warning
Preview changes or save them in file.
Profit :)
This works for any change to the table, just bare in mind that SSMS creates a temporary second table to do the difficult changes like primary column type change.
This works for me in version 18.9 of the app.

Drop one to one relationship tables

I created two tables which are 1 to 1.
So one table has foreign key from another.
How can I drop the tables? I did not use on delete cascade while creating tables.
So I either have to somehow change it, or IDK..
I have done this.
CREATE TABLE hotel(
id_hotel
...
)
CREATE TABLE Manager(
ID_Manager
...
id_hotel FOREIGN KEY ...
)
and then I added
ALTER TABLE Hotel ADD id_manager INT NOT NULL;
ALTER TABLE Hotel ADD FOREIGN KEY (id_manager) REFERENCES Manager(id_manager);
You first have to drop the table with the foreign key in the column, eg: If you have 2 entities one named driving_license and the other person, and you store the id from person in the table driving_license, you have to first drop the table driving_license
Or if you are using MySQL: You can write:
SET_FOREIGN_KEY_CHECKS=0;
//Drop however you want
SET_FOREIGN_KEY_CHECKS=1
For MSSQL you can use:
ALTER TABLE <yourtablename> NOCHECK CONSTRAINT ALL
And then drop your table

Generic SQL Query for Empty Database

I'm searching for a generic SQL query that replaces the following procedures:
-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints
-- --------------------------------------------------
-- --------------------------------------------------
-- Dropping existing tables
-- --------------------------------------------------
Example:
The following query drops foreign keys for specific table. Can it be converted to a generic one? (Please don't suggest dropping the whole database as I don't have permissions.)
SELECT
'ALTER TABLE ' + OBJECT_NAME(parent_object_id) +
' DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')
Question:
How can I empty a database without dropping it?
Edit: Wait Wait, it's not a duplication question! The other question was about emptying rows ( or data ONLY ) keeping relations and tables. I'm trying to drop all data, tables & relations without dropping the database itself!
Check out this answer How to drop all Foreign Key constraints in all tables?
This will drop your foreign keys from all tables, you can either add a drop table into the loop, or create a new loop afterwards to drop the tables

How to drop an inline foreign key in Oracle-SQL using ALTER TABLE?

create table supplier(
.
.
.
city varchar2(16) references city(city_name)
);
What's the correct query?
alter table suppliers modify city varchar2(16);
The problem you have is that you have created a foreign key without giving a name to the constraint. This is bad practice, because it makes it harder to manipulate the constraint, as pretty much all Oracle DDL requires the object name.
When we don't explicitly name the constraints Oracle generates a default one. These are all horribly similar and there is no way of telling what the constraint actually does. For instance, if you had three foreign key constraints on SUPPLIER you would need to join with the USER_CONS_COLUMNS view in order to see which constraint actually enforce a rule on the CITY column.
So, for future reference,
city varchar2(16) constraint city_fk references city(city_name)
Anyway, right now you need to find the defaulted name of the foreign key constraint, so you can drop it. We'll assume you were equally sloppy with the CITY table, so first we need to find its primary key (you can skip this stage if you actually know the name).
select constraint_name
from user_constraints
where table_name = 'CITY'
and constraint_type = 'P'
Next, feed that name into this query:
select constraint_name
from user_constraints
where table_name = 'SUPPLIER'
and constraint_type = 'R'
and r_constraint_name = '&CITY_PK'
Finally, drop the constraint:
alter table supplier drop constraint city_fk
You want to do this:
ALTER TABLE supplier
DROP CONSTRAINT constraint_name
If you didn't give the constraint a explicit name, Oracle asigned one for you so you have to find it first. You can list all the table constraints with, e.g.:
SELECT *
FROM user_constraints
WHERE TABLE_NAME='SUPPLIER'