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

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.

Related

SQL query not executing as whole

So I have a query that should add Primary Key to the Id field:
IF NOT EXISTS(SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL')
BEGIN
DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;
ALTER TABLE BTS.dbo.CAL
ALTER COLUMN Intern INT NOT NULL;
ALTER TABLE BTS.dbo.CAL
ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);
CREATE INDEX CAL$01
ON CAL (Intern);
END
The problem is that when I chose all this code and execute (F5), I get this error:
Whereas when I'm choosing every statement one by one it works as expected:
I am sure that the IF works as expected
I tried to use GO between statements, it's not allowed.
I should execute this code on a large number of tables
Maybe I don't know something about how SQL Server Management Studio executes statements
Before a query is run it is parsed. This is why what you're doing is failing. SQL server is checking the details of the Intern before the script is run. At the point you start to try to run the script, Intern in the table BTS.dbo.CAL is NULLable, and so the script fails.
You can get around this by running the statement to create the primary key cosntraint in a separate scope:
IF NOT EXISTS(
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL'
)
BEGIN
DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;
ALTER TABLE
BTS.dbo.CAL
ALTER COLUMN
Intern
INT NOT NULL;
EXEC sys.sp_executesql N'ALTER TABLE BTS.dbo.CAL ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);';
CREATE INDEX [CAL$01]
ON CAL (Intern);
END'
Even though question is answer, I just wanted to add one more option.
You can separate statments into two separate batches, so that your change is available to the subsequent batch
CREATE TABLE #test(a int null);
-- DDL Changes
if exists(SELECT 1)
BEGIN
ALTER TABLE #test ALTER COLUMN a int not null;
END
GO
-- Index changes
if exists(SELECT 1)
BEGIN
ALTER TABLE #test ADD CONSTRAINT PK_test PRIMARY KEY(a)
END
GO

Script to create or drop all primary keys in Netezza

I am trying to create a script that will drop and create all the primary keys in my Netezza database. Something similar to this article for SQL Server: https://social.technet.microsoft.com/wiki/contents/articles/2321.script-to-create-or-drop-all-primary-keys.aspx
What's the best way to go about that? I found another solution that uses cross apply, but like cursor, that's not supported in Netezza. Thanks!
Here you go:
--DROP CONSTRAINTS
SELECT DISTINCT ' ALTER TABLE '||RTRIM(SCHEMA)||'.'||RELATION|| ' DROP CONSTRAINT '
|| constraintname || ' CASCADE;' from _V_RELATION_KEYDATA
--optional: WHERE DATABASE=<DATABASE>
--OR WHERE SCHEMA='<SCHEMANAME>;
--ADD PK CONSTRAINTS
SELECT DISTINCT ' ALTER TABLE '||RTRIM(SCHEMA)||'.'||RELATION|| ' ADD CONSTRAINT '
|| constraintname || ' PRIMARY KEY('|| trim(trailing ',' from replace(replace
(XMLSerialize(XMLagg(XMLElement('X',attname)))
,'<X>','')
,'</X>',',')) ||' ) INITIALLY IMMEDIATE;'
from _V_RELATION_KEYDATA
GROUP BY SCHEMA,CONSTRAINTNAME, RELATION;
--optional: WHERE DATABASE=<DATABASE>
--OR WHERE SCHEMA='<SCHEMANAME>;
Make sure to run the --ADD PK Constraints and save the DDL output before dropping the constraints

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';