How can we find the name of the constraint from the Database.? - sql

I have table prsl which have auto generated name of the constraint. I want to search where the Database kept these name.
ALTER TABLE [dbo].[PRSL] DROP CONSTRAINT [PK__PRSL__1C1D47DC0BF1ACC7]
Actually, i want to drop these constraints dynamically.
For Example
SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PRSL]')
drop all the constraint which are on a table.
Drop constraint 'when found'

If you're willing to display all constraints of a given table
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where TABLE_NAME = 'YOUR TABLE NAME'
If you want to drop all constraints of the given table use this:
DECLARE #database nvarchar(50)
DECLARE #table nvarchar(50)
set #database = 'dotnetnuke'
set #table = 'tabs'
DECLARE #sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = #database and table_name = #table)
BEGIN
select #sql = 'ALTER TABLE ' + #table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = #database and
table_name = #table
exec sp_executesql #sql
END
It worked for me...Hope it helps...

Related

SQL Server : drop multiple unknown constraints from the same table

I checked the answer given in this SO question , to drop constraints whose names are not known.
In SQL Server, can we assume they will always be in the same format given? (FK__TABLENAME__KEYPREFIX)?
What does T(c) define?
If two such constraints need to be dropped from the same table, is the following correct?
DECLARE #sql1 NVARCHAR(MAX);
DECLARE #sql2 NVARCHAR(MAX);
SELECT
#sql1 = c
FROM
(SELECT
'ALTER TABLE DOC_INVS_1 DROP CONSTRAINT ' + CONSTRAINT_NAME + '; '
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
TABLE_NAME = 'DOC_INVS_1'
AND CONSTRAINT_NAME LIKE 'FK__DOC_INVS___kntr%') T(c);
SELECT
#sql2 = c
FROM
(SELECT
'ALTER TABLE DOC_INVS_1 DROP CONSTRAINT ' + CONSTRAINT_NAME + '; '
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
TABLE_NAME = 'DOC_INVS_1'
AND CONSTRAINT_NAME LIKE 'FK__DOC_INVS___aaaa%') T(c);
EXEC(#sql1);
EXEC(#sql2);
Note
The actual end goal is to add a 'CASCADE ON DELETE' to a foreign key, which had been added to the wrong key. I learned that you can't just add the cascade option by altering, so the approach is to drop both and then create again.

How to drop all tables from a database in sql server 2005 in a statement except one table

I am using sql-server 2005. Initially, for learning purpose I created many tables now I want to drop all those tables except one which is currently I am working on.
Is there any code or query with which I can drop all tables from my that database except that one useful table.
One way I think is to copy that table into new database using SELECT INTO... clause and drop that database but don't know is this a good way to solve this problem.
If the tables aren't very big I'd probably just select them all in the "Object Explorer Details" window in SSMS then hit delete.
For a programmatic solution you could use
EXEC sys.sp_MSforeachtable
N'IF OBJECT_ID(''?'') <> OBJECT_ID(''dbo.YourTableToKeep'')
DROP TABLE ?
'
Both methods might need repeated runs in order to delete all tables involved in FK relationships (a table cannot be deleted if another table has an FK referencing it).
You can use sql to create all drops staments that you needs. For example the next sql query
USE [MyDatabase];
GO
SELECT
replace(
replace('DROP TABLE [{Schema}].[{TableName}];'
,'{Schema}',TABLE_SCHEMA)
,'{TableName}',TABLE_NAME)
FROM
INFORMATION_SCHEMA.TABLES
WHERE
TABLE_NAME NOT IN ('TableNameOne','TableNameTwo')
and get the result executing the query.
Copy first column of the query and paste it in a new query window.
It's easy to see, that you get a list of drop staments for all tables except 'TableNameOne' and 'TableNameTwo',...
Im think that is very simple...
/* Drop all Foreign Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE #name is not null
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint IS NOT NULL
BEGIN
SELECT #SQL = 'ALTER TABLE [dbo].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint) +']'
EXEC (#SQL)
PRINT 'Dropped FK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE #name IS NOT NULL
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint is not null
BEGIN
SELECT #SQL = 'ALTER TABLE [dbo].[' + RTRIM(#name) +'] DROP CONSTRAINT [' + RTRIM(#constraint)+']'
EXEC (#SQL)
PRINT 'Dropped PK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all tables */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP TABLE [dbo].[' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Table: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > #name ORDER BY [name])
END
GO

Finding a Primary Key Constraint on the fly in SQL Server 2005

I have the following SQL:
ALTER TABLE dbo.PS_userVariables DROP CONSTRAINT PK_PS_userVariables;
ALTER TABLE dbo.PS_userVariables ADD PRIMARY KEY (varnumber, subjectID, userID, datasetID, listid, userVarTitle);
Since I have multiple environments, that PK_PS_userVariables constraint name is different on my different databases. How do I write a script that gets that name then adds it into my script?
While the typical best practice is to always explicitly name your constraints, you can get them dynamically from the catalog views:
DECLARE #table NVARCHAR(512), #sql NVARCHAR(MAX);
SELECT #table = N'dbo.PS_userVariables';
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;
ALTER TABLE dbo.PS_userVariables ADD CONSTRAINT ...
SELECT
A.TABLE_NAME,
A.CONSTRAINT_NAME,
B.COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS A,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE B
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME
ORDER BY
A.TABLE_NAME
Ref: Pinal Dave # http://blog.sqlauthority.com/2008/09/06/sql-server-find-primary-key-using-sql-server-management-studio/
DECLARE #TableName varchar(128)
DECLARE #IndexName varchar(128)
DECLARE #Command varchar(1000)
SET #TableName = 'PS_userVariables'
SELECT #IndexName = si.name
FROM sys.tables st
JOIN sys.indexes si ON st.object_id = si.object_id
WHERE st.name = #TableName
AND si.is_primary_key = 1
SET #Command = 'ALTER TABLE dbo.' + QUOTENAME(#Tablename) + ' DROP CONSTRAINT ' + QUOTENAME(#IndexName) + ';
ALTER TABLE dbo.' + QUOTENAME(#Tablename) + ' ADD PRIMARY KEY (varnumber, subjectID, userID, datasetID, listid, userVarTitle);'
My use case was updating primary key constraint names generated by Entity Framework 6 to match the primary key naming convention of Entity Framework Core.
As EF uses migrations, I created both an Up and Down migration script, and created a temporary long-lived table to store the old and new constraint names so that I could roll back if needed.
This is the SQL I used to update the primary key constraint names:
-- create a temporary long-lived table
-- it can be deleted when rollback is no longer needed
CREATE TABLE dbo.__OldPrimaryKeyConstraintNames (
SchemaName NVARCHAR(128) NOT NULL DEFAULT 'dbo',
TableName NVARCHAR(128) NOT NULL,
OldPrimaryKeyConstraintName NVARCHAR(128) NOT NULL,
NewPrimaryKeyConstraintName NVARCHAR(128) NOT NULL
);
-- create a temporary table to hold the data for the script
DECLARE #tbl TABLE (SchemaName NVARCHAR(3), TableName NVARCHAR(128), PrimaryKeyConstraintName NVARCHAR(128));
-- get all primary key constraint names as well as it's schema and table
INSERT INTO #tbl
SELECT SCHEMA_NAME(pk.schema_id), t.name, pk.name
FROM sys.key_constraints pk
INNER JOIN sys.objects t on t.object_id = pk.parent_object_id
WHERE pk.type = 'PK'
-- row count used for iterating through #tbl
DECLARE #RowCount INT = (SELECT COUNT(*) FROM #tbl);
-- variables used when used for iterating through #tbl
DECLARE #SchemaName NVARCHAR(128)
DECLARE #TableName NVARCHAR(128)
DECLARE #OldPrimaryKeyConstraintName NVARCHAR(128)
DECLARE #NewPrimaryKeyConstraintName NVARCHAR(128)
DECLARE #RenameSql NVARCHAR(MAX)
WHILE #RowCount > 0 BEGIN
-- get the primary key constraint name, schema, and table name for this iteration
SELECT #SchemaName = SchemaName, #TableName = TableName, #OldPrimaryKeyConstraintName = PrimaryKeyConstraintName, #NewPrimaryKeyConstraintName = CONCAT('PK_', TableName)
FROM #tbl
ORDER BY PrimaryKeyConstraintName DESC OFFSET #RowCount - 1 ROWS FETCH NEXT 1 ROWS ONLY;
-- store the old and new primary key constraint names
INSERT __OldPrimaryKeyConstraintNames (SchemaName, TableName, OldPrimaryKeyConstraintName, NewPrimaryKeyConstraintName)
VALUES (#SchemaName, #TableName, #OldPrimaryKeyConstraintName, #NewPrimaryKeyConstraintName)
-- perform the rename
SET #RenameSql = 'sp_rename ' + '''' + #SchemaName + '.' + QUOTENAME(#OldPrimaryKeyConstraintName) + '''' + ', ' + '''' + #NewPrimaryKeyConstraintName + ''''
EXEC sp_executeSQL #RenameSql
-- move to the next row
SET #RowCount -= 1;
END
After running this script, dbo.__OldPrimaryKeyConstraintNames should be populated with the old and new constraint names.
This allows us to revert the renaming if required for whatever reason.
This is the SQL I used to revert the primary key constraint names:
-- create a temporary table to hold the data for the script
DECLARE #tbl TABLE (SchemaName NVARCHAR(3), OldPrimaryKeyConstraintName NVARCHAR(128), NewPrimaryKeyConstraintName NVARCHAR(128));
-- get the old and new constraint names as well as it's schema and table name
INSERT INTO #tbl
SELECT SchemaName, OldPrimaryKeyConstraintName, NewPrimaryKeyConstraintName
FROM dbo.__OldPrimaryKeyConstraintNames
-- row count used for iterating through #tbl
DECLARE #RowCount INT = (SELECT COUNT(*) FROM #tbl);
-- variables used when used for iterating through #tbl
DECLARE #SchemaName NVARCHAR(128)
DECLARE #TableName NVARCHAR(128)
DECLARE #OldPrimaryKeyConstraintName NVARCHAR(128)
DECLARE #NewPrimaryKeyConstraintName NVARCHAR(128)
DECLARE #RenameSql NVARCHAR(MAX)
WHILE #RowCount > 0 BEGIN
-- get the old and new constraint name and it's schema for this iteration
SELECT #SchemaName = SchemaName, #OldPrimaryKeyConstraintName = OldPrimaryKeyConstraintName, #NewPrimaryKeyConstraintName = NewPrimaryKeyConstraintName
FROM #tbl
ORDER BY OldPrimaryKeyConstraintName DESC OFFSET #RowCount - 1 ROWS FETCH NEXT 1 ROWS ONLY;
-- revert the rename
SET #RenameSql = 'sp_rename ' + '''' + #SchemaName + '.' + QUOTENAME(#NewPrimaryKeyConstraintName) + '''' + ', ' + '''' + #OldPrimaryKeyConstraintName + ''''
SELECT #RenameSql
EXEC sp_executeSQL #RenameSql
-- move to the next row
SET #RowCount -= 1;
END
-- drop the temporary long-lived table as it is not required
DROP TABLE IF EXISTS dbo.__OldPrimaryKeyConstraintNames

SQL Server: drop table cascade equivalent?

In oracle, to drop all tables and constraints you would type something like
DROP TABLE myTable CASCADE CONSTRAINTS PURGE;
and this would completely delete the tables and their dependencies. What's the SQL server equivalent??
In SQL Server Management Studio, go to Options / SQL Server Object Explorer / Scripting, and enable 'Generate script for dependent objects'. Then right click the table, script > drop to > new query window and it will generate it for you.
I don't believe SQL has a similarly elegant solution. You have to drop any related constraints first before you can drop the table.
Fortunately, this is all stored in the information schema and you can access that to get your whack list.
This blog post should be able to get you what you need:
http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
-- t-sql scriptlet to drop all constraints on a table
DECLARE #database nvarchar(50)
DECLARE #table nvarchar(50)
set #database = 'DatabaseName'
set #table = 'TableName'
DECLARE #sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = #database and table_name = #table)
BEGIN
select #sql = 'ALTER TABLE ' + #table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = #database and
table_name = #table
exec sp_executesql #sql
END
This might be a horrible solution, but I find it's quick. It is similar to Vinnie's answer, but the product of the SQL statement is another series of SQL statements that will delete all constraints and tables.
(
select
'ALTER TABLE ' + tc.table_name + ' DROP CONSTRAINT ' + tc.constraint_name + ';'
from
INFORMATION_SCHEMA.TABLES t
,INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
where
t.table_name = tc.table_name
and tc.constraint_name not like '%_pk'
and tc.constraint_name not like 'pk_%'
and t.table_catalog='<schema>'
) UNION (
select
'DROP TABLE ' + t.table_name + ';'
from
INFORMATION_SCHEMA.TABLES t
where
t.table_catalog='<schema>'
)
This is all fun and games until some table references your table...
Then I must alter the code provided like so :
CREATE PROCEDURE _cascadeConstraints #database nvarchar(30) = NULL, #table nvarchar(60) = NULL
as
DECLARE #sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = #database and table_name = #table)
BEGIN
select #sql = 'ALTER TABLE ' + #table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = #database and
table_name = #table
select #sql = 'ALTER TABLE ' + tc.TABLE_NAME + ' DROP CONSTRAINT ' + tc.CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc join
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc on
(rc.CONSTRAINT_CATALOG = tc.CONSTRAINT_CATALOG and
rc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME) join
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc_pk on
(tc_pk.CONSTRAINT_CATALOG = rc.CONSTRAINT_CATALOG and
tc_pk.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME)
where tc.constraint_catalog = #database
and tc_pk.TABLE_NAME = #table
exec sp_executesql #sql
END
go
Ultimately we are deleting our table.
So we can simply run 2 following command:
ALTER TABLE ... DROP CONSTRAINT ...
DROP TABLE ...
1> ALTER TABLE PRJ_DETAILS DROP CONSTRAINT FK_PRJ_TYPE;
-- Table name and Constraint Name are the parameter
2> DROP TABLE .
First drop constraint with its name associated with it table
Second you can drop table.
It worked for me and its easy also.
I just need delete the foreign key
DECLARE #database nvarchar(50)
DECLARE #TABLE_NAME nvarchar(250)
DECLARE #CONSTRAINT_NAME nvarchar(250)
DECLARE #sql nvarchar(350)
set #database = 'XXX'
DECLARE db_cursor CURSOR FOR
select TABLE_NAME, CONSTRAINT_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = #database and CONSTRAINT_TYPE='FOREIGN KEY'
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #TABLE_NAME, #CONSTRAINT_NAME
WHILE ##FETCH_STATUS = 0
BEGIN
select #sql = 'ALTER TABLE ' + #TABLE_NAME + ' DROP CONSTRAINT ' + #CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = #database and
table_name = #TABLE_NAME
exec sp_executesql #sql
FETCH NEXT FROM db_cursor INTO #TABLE_NAME, #CONSTRAINT_NAME
END
CLOSE db_cursor
DEALLOCATE db_cursor

Drop column and all dependent objects using data definition language

I need to remove a column from a table, but when I try to remove it:
The object 'object_name' is dependent
on column 'column_name'.
ALTER TABLE DROP COLUMN column_name failed because
one or more objects access this
column.
I can look for the dependency in the system tables and remove it manually, but I need to do a migration (using SQL DDL) so all others members of the team just do the update, run the migration and donĀ“t have to mess up up system objects.
Try this code:
Declare #TABLENAME varchar(max), #COLUMN varchar(max)
SET #TABLENAME = 'YOURTableName'
SET #COLUMN = 'YOURColumnName'
Declare #CONSTRAINT varchar(max)
set #CONSTRAINT ='ALTER TABLE '+#TABLENAME+' DROP CONSTRAINT '
set #CONSTRAINT = #CONSTRAINT + (select SYS_OBJ.name as CONSTRAINT_NAME
from sysobjects SYS_OBJ
join syscomments SYS_COM on SYS_OBJ.id = SYS_COM.id
join sysobjects SYS_OBJx on SYS_OBJ.parent_obj = SYS_OBJx.id
join sysconstraints SYS_CON on SYS_OBJ.id = SYS_CON.constid
join syscolumns SYS_COL on SYS_OBJx.id = SYS_COL.id
and SYS_CON.colid = SYS_COL.colid
where
SYS_OBJ.uid = user_id() and SYS_OBJ.xtype = 'D'
and SYS_OBJx.name=#TABLENAME and SYS_COL.name=#COLUMN)
exec(#CONSTRAINT)
and then run your regular alter table:
ALTER TABLE YOURTABLENAME
DROP COLUMN YOURCOLUMNNAME
With the first code you remove all the dependencies on that column and then you can remove it without problems.
EDIT - Removing Default Values Constraints:
The code above does not seems to remove DEFAULT_CONSTRAINTS so, in that case you must also use:
DECLARE #ConstraintName nvarchar(200)
SELECT #ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__') AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = N'__ColumnName__' AND object_id = OBJECT_ID(N'__TableName__'))
IF #ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + #ConstraintName)