Remove foreign key sql? [duplicate] - sql

This question already has answers here:
Drop foreign key without knowing the name of the constraint?
(8 answers)
How do I drop a foreign key in SQL Server?
(8 answers)
How do you drop a default value or similar constraint in T-SQL?
(6 answers)
Closed 3 years ago.
I understand the code remove the constraint
ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <FOREIGN_KEY_NAME>
But I do not know my FK name I did not give it one and have read that is given one automatically.
How can I find this?

Assuming you are asking about SQL Server, you can try this:
DECLARE #table_name varchar(50) = 'MyTable'
DECLARE #fk_name varchar(100)
SELECT #fk_name = CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = #table_name AND CONSTRAINT_TYPE='FOREIGN KEY'
DECLARE #sql nvarchar(200) = 'ALTER TABLE [' + #table_name + '] DROP CONSTRAINT [' + #fk_name + ']'
EXEC sp_executesql #sql

Related

I need to create a SQL table using dynamic SQL

I am trying to write a stored procedure in SSMS that creates a table, along with two columns with the subject of the table as the single parameter. The table must be named t followed by the subject of the table. As for the columns, the first column is an auto-incrementing surrogate key ID field (and the primary key) that is named as the subject of the table, followed by ID.
The second column is a natural key which is named as the subject of the table. For instance, a table to be created with the subject being Student would create a table named tStudent, with a StudentID surrogate key column as well as a natural key column named Student. I am trying to do this using a dynamic SQL statement (which I am new to) and keep running into issues while trying to implement my natural key column.
ALTER PROC spCreateTable
#subjectOfTable varchar(50)
AS
DECLARE #dynamicSQL nvarchar(500),
#tableName varchar(50),
#tableID varchar(50);
SET #tableName = ('t' + #subjectOfTable);
SET #tableID = (#subjectOfTable + 'ID');
SET #dynamicSQL = 'CREATE TABLE ' + #tableName + ' ( '+ #tableID + ' INT NOT NULL PRIMARY KEY IDENTITY(1,1) ' + #subjectOfTable + ' VARCHAR(50) ) ';
EXEC (#dynamicSQL)
GO
I can get it to work correctly while just adding the tableID column, but keep having syntax issues with the natural key column subjectOfTable. Someone please help!

how to delete a primary key which is having auto increment [duplicate]

This question already has answers here:
Finding a Primary Key Constraint on the fly in SQL Server 2005
(4 answers)
Closed 5 years ago.
I need to drop the primary key of a table Student in a SQL Server database.
I have edited in the table and the script I got is
ALTER TABLE dbo.Student
DROP CONSTRAINT PK__Student__9CC368536561EF8B
But when I run this script in SQL Server query browser to drop the primary key
It shows the message
Msg 3728, Level 16, State 1, Line 1
'PK__Student__9CC368536561EF8B' is not a constraint.
Msg 3727, Level 16, State 0, Line 1
To my concern I think PK__Student__9CC368536561EF8B this will be generated randomly
please help me to drop the primary key constraint using script.
Thanks in advance
You can look up the constraint name in the sys.key_constraints table:
SELECT name
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = Object_id('dbo.Student');
If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:
DECLARE #table NVARCHAR(512), #sql NVARCHAR(MAX);
SELECT #table = N'dbo.Student';
SELECT #sql = 'ALTER TABLE ' + #table
+ ' DROP CONSTRAINT ' + name + ';'
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = OBJECT_ID(#table);
EXEC sp_executeSQL #sql;
This code is from Aaron Bertrand (source).
simply click
'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'
and run the below query is :
Query:alter Table 'TableName' drop constraint PK__TableName__30242045
The answer I got is that variables and subqueries
will not work and we have to user dynamic SQL script. The following works:
DECLARE #SQL VARCHAR(4000)
SET #SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '
SET #SQL = REPLACE(#SQL, '|ConstraintName|', ( SELECT name
FROM sysobjects
WHERE xtype = 'PK'
AND parent_obj = OBJECT_ID('Student')))
EXEC (#SQL)

SQL Server 2008 Script to Drop PK Constraint that has a System Generated Name

I am trying to add a clustered index to an existing table in SQL Server 2008, and it needs to be an automated script, because this table exists on several databases across several servers.
In order to add a clustered index I need to remove the PK constraint on the table, and then re-add it as unclustered. The problem is the name of the PK constraint is auto-generated, and there is a guid appended to the end, so it's like "PK_[Table]_D9F9203400."
The name is different across all databases, and I'm not sure how to write an automated script that drops a PK constraint on a table in which I don't know the name of the constraint. Any help is appreciated!
UPDATE:
Answer below is what I used. Full script:
Declare #Val varchar(100)
Declare #Cmd varchar(1000)
Set #Val = (
select name
from sysobjects
where xtype = 'PK'
and parent_obj = (object_id('[Schema].[Table]'))
)
Set #Cmd = 'ALTER TABLE [Table] DROP CONSTRAINT ' + #Val
Exec (#Cmd)
GO
ALTER TABLE [Table] ADD CONSTRAINT PK_Table
PRIMARY KEY NONCLUSTERED (TableId)
GO
CREATE UNIQUE CLUSTERED INDEX IX_Table_Column
ON Table (Column)
GO
You can look up the name of the constraint and write a bit of dynamic SQL to handle the drop.
SELECT name
FROM sys.key_constraints
WHERE parent_object_id = object_id('YourSchemaName.YourTableName')
AND type = 'PK';

I need to remove a unique constraints that I don't know the names of

I maintain a product that is installed at multiple locations which as been haphazardly upgraded. Unique constraints were added to a number of tables, but I have no idea what the names are at any particular instance. What I do know is the table/columnname pair that has the unique constraints and I would like to write a script to delete any unique constraint on these column/table combinations.
This is SQL Server 2000 and later. Something that works on 2000/2005/2008 would be best!
This script would generate a list of ALTER TABLE..... DROP CONSTRAINT.... commands, which you can then copy+paste and execute (or tweak before executing as needed) to drop all unique constraints / unique indices:
SELECT
'ALTER TABLE ' + OBJECT_NAME(so.parent_obj) + ' DROP CONSTRAINT ' + so.name
FROM sysobjects so
WHERE so.xtype = 'UQ'
I hope it should work on all SQL Server versions from 2000 to 2008 R2.
This is way trickier than it seems like it should be, I found a way that works for me - I believe it will only work on SQL Server 2005 or above. Here's the full scenario:
Table has been created with a unique constraint on a column, ex:
CREATE TABLE table_name (
id bigint identity not null,
column_name varchar(255) not null,
primary key(id),
unique (column_name)
);
Sometime later, it is discovered that this unique constraint is not desired.
INSERT INTO table_name(column_name) VALUES('col1');
results in: Violation of UNIQUE KEY constraint 'UQ__table_na__9FA0BA59160F4887'. Cannot insert duplicate key in object 'dbo.table_name'.
If you have manual control of this db and can running SQL directly on it is possible, just do:
ALTER TABLE table_name DROP CONSTRAINT UQ__table_na__9FA0BA59160F4887;
In my case, these scripts will have been run on different environments and the keys won't have identical names, so in order to remove the constraint I need SQL which takes the table and column name as input and figures out the rest.
DECLARE #table_name nvarchar(256)
DECLARE #col_name nvarchar(256)
DECLARE #Command nvarchar(1000)
-- set your table and column name here:
SET #table_name = N'table_name'
SET #col_name = N'column_name'
SELECT #Command = 'ALTER TABLE ' + #table_name + ' DROP CONSTRAINT ' + d.name
FROM sys.tables t
JOIN sys.indexes d ON d.object_id = t.object_id AND d.type=2 and d.is_unique=1
JOIN sys.index_columns ic on d.index_id=ic.index_id and ic.object_id=t.object_id
JOIN sys.columns c on ic.column_id = c.column_id and c.object_id=t.object_id
WHERE t.name = #table_name and c.name=#col_name
--if you want to preview the generated command before running
SELECT #Command
EXEC sp_executesql #Command;
That removes the unique constraint on the column and allows the insert to proceed.
This page has a quick and dirty way to pull out all the CONSTRAINTs in the database, and from there you could build up dynamic SQL to drop them:
SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT';

How do I drop all foreign-key constraints on a table in Sql Server 2000?

How do I drop all foreign-key constraints on a table in SQL Server 2000 using T-SQL?
If simply disabling constraints is an option here, you can use:
ALTER TABLE myTable NOCHECK CONSTRAINT all
then you can switch them back on simply using:
ALTER TABLE myTable WITH CHECK CHECK CONSTRAINT all
If you want to disable constrains in all tables you can use:
-- disable all constraints
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
-- enable all constraints
exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
More in the question: Can foreign key constraints be
temporarily disabled using TSQL?
But if you need to drop constraints permanently you can use this script posted on databasejurnal.com.
Just modify it slightly to only drop the foreign keys
create proc sp_drop_fk_constraints
#tablename sysname
as
-- credit to: douglas bass
set nocount on
declare #constname sysname,
#cmd varchar(1024)
declare curs_constraints cursor for
select name
from sysobjects
where xtype in ('F')
and (status & 64) = 0
and parent_obj = object_id(#tablename)
open curs_constraints
fetch next from curs_constraints into #constname
while (##fetch_status = 0)
begin
select #cmd = 'ALTER TABLE ' + #tablename + ' DROP CONSTRAINT ' + #constname
exec(#cmd)
fetch next from curs_constraints into #constname
end
close curs_constraints
deallocate curs_constraints
return 0
Here you go: (not tested on SQL2000, but should be ok)
Generates 'disables':
SELECT 'IF EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N''[dbo].' + FK +''')
AND parent_object_id = OBJECT_ID(N''[dbo].' + PT + '''))
ALTER TABLE ' + PT + ' NOCHECK CONSTRAINT ' + FK + ';'
FROM
(SELECT
OBJECT_NAME(constraint_object_id) as FK,
OBJECT_NAME(parent_object_id) as PT
FROM [sys].[foreign_key_columns] ) T
ORDER BY FK
Generates 'enables':
SELECT 'ALTER TABLE ' + PT + ' WITH CHECK CHECK CONSTRAINT ' + FK + ';'
FROM
(SELECT
OBJECT_NAME(constraint_object_id) as FK,
OBJECT_NAME(parent_object_id) as PT
FROM [sys].[foreign_key_columns] ) T
ORDER BY FK
Update: Oops, I thought you wanted it for all tables :) You can just modify above for your single table.
I think you'll find that there is no easy way to drop constraints on a table in SQL Server 2000. That said, there are plenty of people who have written scripts that can identify and remove/disable/recreate foreign key constraints. One example is at http://www.mssqltips.com/tip.asp?tip=1376 - but I haven't tested it on SQL Server 2000.
EDIT: Here is another example that generates drop/create scripts for you.