How to delete a primary key which doesn't have a name? - sql-server

I am using SQL Server. Is there a way to drop the primary key which doesn't have a name?

It does have a name. Even if you don't name it explicitly SQL Server will auto create a name prefixed PK and based on the table name and the object_id of the constraint.
You can use the following query to see what it is.
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE='PRIMARY KEY' AND TABLE_SCHEMA='dbo' AND TABLE_NAME='T'
The constraint name is required in the grammar for the DROP CONSTRAINT operation
ALTER TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name
{
....
DROP
{
[ CONSTRAINT ] constraint_name
[ WITH ( <drop_clustered_constraint_option> [ ,...n ] ) ]
| COLUMN column_name
} [ ,...n ]

Primary key always has a name. If you didn't specify it in 'create table' or 'alter table' statement, the key name is auto-generated.
In the query bellow replace X with the name of your table and run the script.
It will drop the primary key.
declare #TableName sysname = 'X'
declare #PrimaryKeyName sysname = (
select name
from sys.key_constraints
where type = 'PK' and parent_object_id = object_id(#TableName))
execute ('alter table ' + #TableName + ' drop constraint ' + #PrimaryKeyName)
It is always a good idea to specify explicit names for constraints, because if you run 'create/alter table' script on different databases, all of them will have different constraint name created.
Later, when you need to delete the constraints you need to run this workaround script, instead just running simple 'alter table drop constraint' statement.

CREATE TABLE #Tempbox (Id int primary key identity(1,1), Name varchar(200) unique)
creating a table with column Id, and name, notice it doesn't have constraint name.
Well, if you don't set contraint name for column, sql server provides their own default unique constraint name to constraint like primary key, unique and so on.
1. Let's insert some value in our #Tempbox table
1. insert into #tempbox values ('Abc')
2. insert into #tempbox values ('Abc')
unique key violation error shown by sql server along with constraint name.
**Msg 2627, Level 14, State 1, Line 5
Violation of UNIQUE KEY constraint **'UQ__#Tempbox__737584F6A146D511'**. Cannot insert duplicate key in object 'dbo.#Tempbox'. The duplicate key value is (dsaf).
The statement has been terminated.**
you got the constraint name now.. which is 'UQ__#Tempbox__737584F6A146D511'
now let's drop the column with constraint. Remember you can't drop a column if it is using a constraint so in order to drop that column you will have to drop first constraint and after column.
ALTER TABLE #Tempbox drop constraint UQ__#Tempbox__737584F6A146D511; -- constraint is dropped
now drop the column
alter table #tempbox drop column Name
Now use the same procedure for primary key column
INSERT INTO #Tempbox (Id, Name) VALUES (1,'Abc')
INSERT INTO #Tempbox (Id, Name) VALUES (1,'Abc')
Error :
Msg 2627, Level 14, State 1, Line 3
Violation of PRIMARY KEY constraint **'PK__#Tempbox__3214EC07B3D09900'**. Cannot insert duplicate key in object 'dbo.#Tempbox'. The duplicate key value is (1).
The statement has been terminated.
drop constraint and drop column.
Another way to find the constraint name..
USE Adventure
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE='PRIMARY KEY' AND TABLE_SCHEMA='pERSON' AND TABLE_NAME='PERSON'

Related

SQL Server 8111 - but column is NOT NULLABLE

I want to add a primary key constraint to an existing column on an existing table that contains data. The column is not nullable.
However, when I call
alter table mytable add primary key (mycolumn)
I get an 8111:
Msg 8111, Level 16, State 1, Line 2 Cannot define PRIMARY KEY
constraint on nullable column in table 'mytable'
Even if I call both instructions in a row:
alter table mytable alter column mycolumn INT NOT NULL;
alter table mytable add primary key (mycolumn)
I still get an 8111
- and the column description in SQL Server Management Studio confirms, that mycolumn is set to NOT NULL
What can I do this?
You need to separate your batches. It would be best to include the schema name as well.
alter table dbo.mytable alter column mycolumn INT NOT NULL;
go
alter table dbo.mytable add primary key (mycolumn);
rextester demo: http://rextester.com/TZLEWP56616

Alter column length with or without data in table

Its about ORACLE (PL/SQL) script. I am not very familiar with databse to be honest.
I want to alter the length of a string in a column from 30 to 60. It is not null column.
If the table is empty and I run following script then it works:
alter table [TABLE_NAME] add ( NEW_COLUMN NVARCHAR2(60) DEFAULT 'null' NOT NULL );
/
alter table [TABLE_NAME] DROP CONSTRAINT PK_[TABLE_NAME];
/
begin
for rec in ( select * from [TABLE_NAME] )
loop
update [TABLE_NAME] set NEW_COLUMN =rec.OLD_COLUMN where Name_ID=rec.Name_ID;
end loop;
end;
/
alter table [TABLE_NAME] drop column OLD_COLUMN;
/
alter table [TABLE_NAME] rename column NEW_COLUMN to OLD_COLUMN;
/
alter table [TABLE_NAME] add CONSTRAINT PK_[TABLE_NAME] PRIMARY KEY(Name_ID);
/
But if the table has values then this script does not work.
It gives error: Cannot drop constraint - nonexistent constraint
However, if I remove lines about constraints (second and second last) then it works.
Now I don’t know if the table will be empty or it will have data so I need a script that can work in both the situations. Can anyone help please?
Following script for creating table:
CREATE TABLE TABLE_NAME
(
Name_ID NVARCHAR2(7) NOT NULL,
OLD_COLUMN NVARCHAR2(30) NOT NULL,
CONSTRAINT PK_TABLE_NAME PRIMARY KEY(Name_ID, OLD_COLUMN)
)
/
So while creating table it puts the primary key constraints but while updating table it drops this constraints somehow. I am simplyfying the sitation here. The tables are updates through java code. What I need to do is make a script that work in both situations - with data or just after creating table and modifying the column.
The following script works for me, regardless of whether the insert statement is present or not (ie. the table has or has not data):
CREATE TABLE TABLE_NAME
(
Name_ID NVARCHAR2(7) NOT NULL,
OLD_COLUMN NVARCHAR2(30) NOT NULL,
CONSTRAINT PK_TABLE_NAME PRIMARY KEY(Name_ID, OLD_COLUMN)
);
insert into table_name (name_id, old_column)
values ('test', 'test_old_col');
commit;
alter table table_name add (new_column nvarchar2(60) default 'null' not null);
update table_name set new_column = old_column;
commit;
alter table table_name drop constraint PK_TABLE_NAME;
alter table table_name drop column old_column;
alter table table_name rename column new_column to old_column;
alter table TABLE_NAME add CONSTRAINT PK_TABLE_NAME PRIMARY KEY(Name_ID, old_column);
drop table table_name;
I have assumed that you meant to recreate the primary key with the old_column in it, otherwise you would be unable to recreate it if there are any duplicate values present in the name_id column.
As an alternative, you can save the old data and create a new table with new parameters. Then insert the old values.
In SQL Server Management Studio:
"your database" => task => generatescripts => select specific database object => "your table" => advanced => types of data to script - schema and data => generate

vsdbcmd.exe generate drop constraint instructions without constraint name

When generating a diff script between two dbschema with vsdbcmd.exe, I sometime obtain an unexpected output, containing some drop constraint without the name of the constraint :
GO
PRINT N'Dropping On column: ColumnName ...';
GO
ALTER TABLE TableName DROP CONSTRAINT ;
In our schema, this column has a default value constraint, with an auto generated name. I expected vsdbcmd.exe to generate a valid ALTER TABLE sql statement, as specified in the msdn library :
ALTER TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name DROP { [ CONSTRAINT ] constraint_name | COLUMN column_name }
Do you have any idea of what could prevent vsdbcmd.exe to generate a valid sql statement ?
This issue only occurs when the constraint has a generated name. Explicitly named constraint are not impacted.
Therefore, this solution is to name every constraint.

SQL Server: How do I add a constraint to an existing table but only if the constraint does not already exist?

I need to add a constraint to an existing SQL server table but only if it does not already exist.
I am creating the constraint using the following SQL.
ALTER TABLE [Foo] ADD CONSTRAINT [FK_Foo_Bar] FOREIGN KEY ([BarId]) REFERENCES [Bar] ([BarId]) ON UPDATE CASCADE ON DELETE CASCADE
I'm hoping I can add some SQL to the begining of the SQL to test for the existence of the constraint but I have no idea how.
Personally I would drop the existing constraint, and recreate it - in case the one that is already there is in some way different
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[MyFKName]') AND OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE dbo.MyTableName DROP CONSTRAINT MyFKName
GO
ALTER TABLE dbo.MyTableName ADD CONSTRAINT [MyFKName] ...
The current, more modern, code I am using is:
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[MyFKName]') AND parent_object_id = OBJECT_ID(N'[dbo].[MyTableName]'))
ALTER TABLE dbo.[MyTableName] DROP CONSTRAINT [MyFKName]
GO
ALTER TABLE dbo.[MyTableName] ADD CONSTRAINT [MyFKName] FOREIGN KEY ...
not sure if there is any advantage of checking sys.objects ... or sys.foreign_keys ... but at some point I decided on sys.foreign_keys
Starting with SQL2016 new "IF EXISTS" syntax was added which is a lot more readable:
-- For SQL2016 onwards:
ALTER TABLE dbo.[MyTableName] DROP CONSTRAINT IF EXISTS [MyFKName]
GO
ALTER TABLE dbo.[MyTableName] ADD CONSTRAINT [MyFKName] FOREIGN KEY ...
I'd recommend using the INFORMATION_SCHEMA.TABLE_CONSTRAINTS view. It's portable across different database engines:
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='Foo'
AND CONSTRAINT_NAME='FK_Foo_Bar'
AND CONSTRAINT_TYPE='FOREIGN KEY'
Check if the constraint already exists before adding it -
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_Foo_Bar')
BEGIN
ALTER TABLE dbo.MyTableName ADD CONSTRAINT [MyFKName] ...
END
Alter table tableName add constraint constraintname default 0 for columnname
You can provide constraintname as you want without single quote
Drop the default constraint and create your own. ALTER table TABLE_NAME drop constraint CONSTRAINT NAME
GO
ALTER TABLE [dbo].[TABLE_NAME] ADD CONSTRAINT [DF_TABLE_NAME_COLUMN_NAME] FOR [COLUMN_NAME]
Very simple:
IF OBJECT_ID('Schema.keyname') IS NULL
ALTER TABLE Schema.tablename ADD CONSTRAINT keyname...

How do I drop a foreign key in SQL Server?

I have created a foreign key (in SQL Server) by:
alter table company add CountryID varchar(3);
alter table company add constraint Company_CountryID_FK foreign key(CountryID)
references Country;
I then run this query:
alter table company drop column CountryID;
and I get this error:
Msg 5074, Level 16, State 4, Line 2
The object 'Company_CountryID_FK' is dependent on column 'CountryID'.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE DROP COLUMN CountryID failed because one or more objects access this column
I have tried this, yet it does not seem to work:
alter table company drop foreign key Company_CountryID_FK;
alter table company drop column CountryID;
What do I need to do to drop the CountryID column?
Thanks.
Try
alter table company drop constraint Company_CountryID_FK
alter table company drop column CountryID
This will work:
ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]
I think this will helpful to you...
DECLARE #ConstraintName nvarchar(200)
SELECT
#ConstraintName = KCU.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU
ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE
KCU.TABLE_NAME = 'TABLE_NAME' AND
KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME'
IF #ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop CONSTRAINT ' + #ConstraintName)
It will delete foreign Key Constraint based on specific table and column.
First check of existence of the constraint then drop it.
if exists (select 1 from sys.objects where name = 'Company_CountryID_FK' and type='F')
begin
alter table company drop constraint Company_CountryID_FK
end
alter table company drop constraint Company_CountryID_FK
I don't know MSSQL but would it not be:
alter table company drop **constraint** Company_CountryID_FK;
You can also Right Click on the table, choose modify, then go to the attribute, right click on it, and choose drop primary key.
Are you trying to drop the FK constraint or the column itself?
To drop the constraint:
alter table company drop constraint Company_CountryID_FK
You won't be able to drop the column until you drop the constraint.

Resources