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
I am trying to add a new column to all tables in db which is a foreign key to one of the table. Ideally I should add the column to all tables instead of the table that the foreign key reference to.
How do I combine these two SQL statements to only one statement?
// Get all tables except the foreign key reference to
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="arthurMurray"
AND TABLE_TYPE="BASE TABLE"
AND TABLE_NAME!="Competitions";
// Add compeition_id to table as a foreign key to competitions table
ALTER TABLE t
ADD competition_id INTEGER,
ADD CONSTRAINT FOREIGN KEY(competition_id) REFERENCES Competitions(id);
Any help will be appreciate!
Please check this
EXEC sp_MSforeachtable '
if not exists (select * from sys.columns
where object_id = object_id(''?'')
and name = ''CreatedOn'')
begin
ALTER TABLE ? ADD CreatedOn datetime NOT NULL DEFAULT getdate();
end';
you ca use below query to generate your alter statement then you ca copy paste and execute below script.
SELECT
'ALTER TABLE ' + TABLE_NAME + 'ADD competition_id INTEGER, ADD CONSTRAINT FOREIGN KEY(competition_id) REFERENCES Competitions(id);'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='whatever_schema'
AND TABLE_TYPE='BASE TABLE'
AND TABLE_NAME!='Competitions';
Should the second ALTER TABLE CHECK CONSTRAINT be in an IF (NOT) EXISTS so that the script can be executed repeatedly?
IF NOT EXISTS (
SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_NAME ='fk_RoleId'
)
BEGIN
ALTER TABLE [dbo].[webpages_UsersInRoles] WITH CHECK ADD CONSTRAINT [fk_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[webpages_Roles] ([RoleId])
END
GO
-- Put me in an IF ... () BEGIN ... END?
ALTER TABLE [dbo].[webpages_UsersInRoles] CHECK CONSTRAINT [fk_RoleId]
GO
It doesn't cause any errors, but if it should be in an IF clause, how do you test if it has been ran (what can the if contain)?
If you do want a check (it's not necessary), sys.foreign_keys has a column is_not_trusted:
FOREIGN KEY constraint has not been verified by the system.
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'
I got the problem is when I run following command in Oracle, I encounter the error.
Truncate table mytable;
Errors:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
I found that, this mytable has relationship with other tables. That's why Truncate command cannot proceed anymore. How to delete data from myTable with the SQL scripts using Truncate command?
You have to swap the TRUNCATE statement to DELETE statements, slower and logged but that's the way to do it when constraints are in place.
DELETE mytablename;
Either that or you can find the foreign keys that are referencing the table in question and disable them temporarily.
select 'ALTER TABLE '||TABLE_NAME||' DISABLE CONSTRAINT '||CONSTRAINT_NAME||';'
from user_constraints
where R_CONSTRAINT_NAME='<pk-of-table>';
Where pk-of-table is the name of the primary key of the table being truncated
Run the output of the above query. When this has been done, remember to enable them again, just change DISABLE CONSTRAINT into ENABLE CONSTRAINT
this page offers a very good solution ...
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
I'm here copying from it the Solution:
Find the referenced ENABLED foreign key constraints and disable them.
truncate/delete from the table .
using any text editor .. just change disable to enable in the output you get from the query , then run it.
select 'alter table '||a.owner||'.'||a.table_name||' disable constraint '||a.constraint_name||';'
from all_constraints a, all_constraints b
where a.constraint_type = 'R' and a.status='ENABLED'
and a.r_constraint_name = b.constraint_name
and a.r_owner = b.owner
and b.table_name = upper('YOUR_TABLE');
The error message is telling you that there are other table(s) with a foreign key constraint referring to your table.
According to the Oracle docs
You cannot truncate the parent table
of an enabled foreign key constraint.
You must disable the constraint before
truncating the table.
The syntax for disabling a foreign key is:
ALTER TABLE table_name disable
CONSTRAINT constraint_name;
Issue:
Error “ORA-02266: unique/primary keys in table referenced by enabled foreign keys” when trying to truncate a table.
Error Message:
SQL> truncate table TABLE_NAME;
truncate table TABLE_NAME
*
ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
Solution:
-- Find the referenced foreign key constraints.
SQL> select 'alter table '||a.owner||'.'||a.table_name||' disable constraint '||a.constraint_name||';'
2 from all_constraints a, all_constraints b
3 where a.constraint_type = 'R'
4 and a.r_constraint_name = b.constraint_name
5 and a.r_owner = b.owner
6 and b.table_name = 'TABLE_NAME';
'ALTER TABLE'||A.OWNER||'.'||A.TABLE_NAME||'DISABLE CONSTRAINT'||A.CONSTRAINT_NAME||';'
---------------------------------------------------------------------------------------------------------
alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT disable constraint CONSTRAINT_NAME;
alter table SCHEMA_NAME.TABLE_NAME_LOCATION disable constraint CONSTRAINT_NAME;
-- Disable them
alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT disable constraint CONSTRAINT_NAME;
alter table SCHEMA_NAME.TABLE_NAME_LOCATION disable constraint CONSTRAINT_NAME;
-- Run the truncate
SQL> truncate table TABLE_NAME;
Table truncated.
-- Enable the foreign keys back
SQL> select 'alter table '||a.owner||'.'||a.table_name||' enable constraint '||a.constraint_name||';'
2 from all_constraints a, all_constraints b
3 where a.constraint_type = 'R'
4 and a.r_constraint_name = b.constraint_name
5 and a.r_owner = b.owner
6 and b.table_name = 'TABLE_NAME';
'ALTER TABLE'||A.OWNER||'.'||A.TABLE_NAME||'ENABLE CONSTRAINT'||A.CONSTRAINT_NAME||';'
--------------------------------------------------------------------------------
alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT enable constraint CONSTRAINT_NAME;
alter table SCHEMA_NAME.TABLE_NAME_LOCATION enable constraint CONSTRAINT_NAME;
-- Enable them
alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT enable constraint CONSTRAINT_NAME;
alter table SCHEMA_NAME.TABLE_NAME_LOCATION enable constraint CONSTRAINT_NAME;
Oracle 12c introduced a feature to truncate a table that is a parent of a referential integrity constraint having ON DELETE rule.
Instead of truncate table tablename; use:
TRUNCATE TABLE tablename CASCADE;
From Oracle truncate table documentation:
If you specify CASCADE, then Oracle Database truncates all child tables that reference table with an enabled ON DELETE CASCADE referential constraint. This is a recursive operation that will truncate all child tables, granchild tables, and so on, using the specified options.
A typical approach to delete many rows with many constraints is as follows:
create mytable_new with all the columns but without constrains (or create constraints disabled);
copy whatever data you need from mytable to mytable_new.
enable constraints on mytable_new to see that everything is ok.
alter any constraints that reference mytable to reference mytable_new instead and see that everything is ok.
drop table mytable.
alter table mytable_new rename to mytable.
It's far faster than deleting a million records with many slow constraints.
I had the similar issue and I sorted it out by the following scripts.
begin
for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
(select b.table_name from user_constraints b where b.table_name like '%BIN%')
and a.constraint_type not in 'P')
LOOP
execute immediate 'alter table '||i.table_name||' disable constraint '||i.constraint_name||'';
end loop;
end;
/
truncate table TABLE_1;
truncate table TABLE_2;
begin
for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
(select b.table_name from user_constraints b where b.table_name like '%BIN%')
and a.constraint_type not in 'P')
LOOP
execute immediate 'alter table '||i.table_name||' enable constraint '||i.constraint_name||'';
end loop;
end;
/
This script will first disable all the Constraints. Truncates the data in the tables and then enable the contraints.
Hope it helps.
cheers..
TRUNCATE TABLE TEST2 DROP ALL STORAGE;
This statement Actually works when there is an foreign key constraint applied on a .table
As mentioned by the error message, you cannot truncate a table that is referenced by enabled foreign keys. If you really want to use the truncate DDL command, disable the foreign key constraint first, run the truncate command, and enable it back.
Reference: Difference between TRUNCATE, DELETE and DROP commands