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
Related
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.
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;
Code:
ALTER TABLE tblUser
DROP COLUMN Mobile
Error:
ALTER TABLE DROP COLUMN Mobile failed because one or more objects access this column.
This column had values in Table. How can I delete all objects that access this column?
How can I DROP COLUMN with values?
how can do it with code? How can I delete all constraints in column automatically?
ALTER TABLE DROP COLUMN Mobile failed because one or more objects access this column.
Your column won't be deleted. Because one column or multiple columns are getting reference from this column that you want to delete.
So first, you will have to find in which table your column is being referenced by below query.
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'TABLENAME'
It will show you all constraints of all tables of your current database. You need to find it and remove the constraint. After that your column will be deleted successfully because there is no reference of your column in any table.
To remove constraint from column - use below query
alter table tablename
drop constraint constraintid
SQL Search is a great tool. I will search for your all the objects which are using the targeted object.
You can easily find where your column is being used, then simply you can modify or drop that objects too.
Use below query to find the constraints name for particular tablename
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'TABLENAME'
Noe you can see the constraints name under constraint_name column, drop all constraint using below syntax
ALTER TABLE TABLENAME DROP CONSTRAINT CONSTRATINTSNAME
After that you can use below statement to drop the column
ALTER TABLE TABLENAME DROP COLUMN COLUMNNAME
You need to know what those constraints are and what their names are in order to drop them; there's nothing in SQL Server to say DROP ALL CONSTRAINTS and just do it. – marc_s yesterday
I'm trying to drop a table in Northwind, and I'm getting:
ALTER TABLE DROP COLUMN Region failed because one or more objects access this column.
I'm using:
use [NorthWind]
go
alter table dbo.Customers
drop column Region
I guess it's because there is a constraint on the column Region. How do I find out which constraint I need to remove?
EXEC sp_MSforeachtable #command1="ALTER TABLE ? NOCHECK CONSTRAINT ALL"
GO
OR
ALTER TABLE table_Name NOCHECK CONSTRAINT all
OR
ALTER TABLE table_Name NOCHECK CONSTRAINT constraint_name
Then try with your SQL.
Please use this when you really want to drop constraints no matter other tables affected.
If disabling the constraints is not enough, you will have to drop the constraints.
You must drop Constraint first and then drop the table.If you have SQL Server Management Studio you can select the constraint and delete it using GUI. Or you can use command line to drop your constraints
How to remove foreign key constraint in sql server?. Taken from this answer
ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <FOREIGN_KEY_NAME>
If you want to go via Sql Server Management Studio on the object explorer window, right click on the object you want to drop,then click view dependencies.
First, you should know the ForeignKey - Constraint. After that, you must drop it.
Something like this:
-- looking for the Constraint's name related the dbo.Customers table
SELECT Table_Name,Constraint_Name
FROM Information_Schema.CONSTRAINT_TABLE_USAGE
WHERE Table_Name 'Customers'
-- Drop/Delete the founded constraint
ALTER TABLE [dbo].[Customers] DROP CONSTRAINT [FOREIGN_KEY_NAME]
Then, you'll run your actual script.
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