Drop default constraint in SQL Server on many columns - sql

For SQL Server 2008 R2 I want to remove default constraints for date columns that allow null and the constraint contains 1899. And I want a script that can tested and then executed in live. I don't wan't to fiddle with this in live environment. Another reason for a script is that there is several databases with the same scheme
With help from Google I have the following script that list columns
SELECT tables.name, all_columns.name, all_columns.is_nullable, default_constraints.name, default_constraints.definition
FROM
sys.all_columns
INNER JOIN
sys.tables
ON all_columns.object_id = tables.object_id
INNER JOIN
sys.schemas
ON tables.schema_id = schemas.schema_id
INNER JOIN
sys.default_constraints
ON all_columns.default_object_id = default_constraints.object_id
WHERE
schemas.name = 'dbo'
and default_constraints.definition like '%1899%'
and all_columns.is_nullable = 1
order by tables.name, all_columns.name, default_constraints.name
Now this list over hundred columns. The next script do what I want for the column CargoPool.Created. But how can I iterate all rows created from my first script ?
DECLARE #tableName VARCHAR(MAX) = 'CargoPool'
DECLARE #columnName VARCHAR(MAX) = 'Created'
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 = #columnName AND object_id = OBJECT_ID(#tableName))
IF #ConstraintName IS NOT NULL
EXEC('ALTER TABLE '+#tableName+' DROP CONSTRAINT ' + #ConstraintName)

If you want to drop all the constraints from your first query, you can build up a dynamic SQL with the results of that query and then execute it:
DECLARE #sql AS NVARCHAR(MAX) = N''
SELECT #sql = #sql + N'ALTER TABLE '
+ QUOTENAME(schemas.name) + N'.' + QUOTENAME(tables.name)
+ N' DROP CONSTRAINT ' + QUOTENAME(default_constraints.name) + N'; '
FROM
sys.all_columns
INNER JOIN
sys.tables
ON all_columns.object_id = tables.object_id
INNER JOIN
sys.schemas
ON tables.schema_id = schemas.schema_id
INNER JOIN
sys.default_constraints
ON all_columns.default_object_id = default_constraints.object_id
WHERE
schemas.name = N'dbo'
and default_constraints.definition like N'%1899%'
and all_columns.is_nullable = 1
order by tables.name, all_columns.name, default_constraints.name
exec sp_executesql #sql;

Related

How to drop foreign keys of a particular column

I have created a foreign key without specifying the name so sql server has created it with auto generated name. Now I want to drop the column which has this foreign key. The problem is that i don't know the name of this foreign key. Is there any way to drop all the foreign keys for particular column in particular table?
So far I've found this script which drops all default constraints for column
DECLARE #tableName VARCHAR(MAX)
DECLARE #ConstraintName nvarchar(200)
DECLARE #columnName VARCHAR(MAX)
SET #tableName = 'tablename'
SET #columnName = 'columnname'
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 = #columnName AND object_id = OBJECT_ID(#tableName))
IF #ConstraintName IS NOT NULL
BEGIN
EXEC('ALTER TABLE '+#tableName+' DROP CONSTRAINT ' + #ConstraintName)
END
ALTER TABLE [tablename] DROP COLUMN columnname
GO
But it doesn't help with foreign key constraints.
If you want to get more information about FK and specifically about a particular scheme and table than you can use.
SELECT
t.Name as TableName,
c.name as ColumnName,
fk.name as FK_NAME
FROM sys.foreign_keys as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on c.object_id = t.object_id
inner join sys.schemas as sc on t.schema_id = sc.schema_id
WHERE sc.name = 'Schema' and t.name = 'Table' and c.name = 'Column'
If you are interested only about certain column then u can use Ross Presser answer.
Also if you want to drop all fk constraint you can execute this:
Declare #sql nvarchar(4000)
SET #sql = N'';
SELECT #sql = #sql + '
ALTER TABLE [' + sc.NAME + '].[' + OBJECT_NAME(fk.parent_object_id) + ']' + ' DROP CONSTRAINT ' + '[' + fk.NAME + ']
'
FROM sys.foreign_keys as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on c.object_id = t.object_id
inner join sys.schemas as sc on t.schema_id = sc.schema_id
WHERE sc.name = 'schemaName' and c.name = 'columnName' -- you can include and fk name
ORDER BY fk.NAME
PRINT #sql;
--EXEC sys.sp_executesql #sql;
You can get all the constraint list along with the names assigned to particular tables with the help of the below query:
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='YourTableName';
Once you find the constraint you want to delete you can do it with the help of below query:
ALTER TABLE Orders
DROP CONSTRAINT constraint_name;
You can find all constraints throughout the database that use the column:
SELECT * FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU
WHERE CCU.COLUMN_NAME='someColumn'
The output gives the constraint name and the table it is attached to.
Here's an example to find foreign keys using the system views (which aren't amazingly well documented):
select fk.name as ForeignKeyName
, t_parent.name as ParentTableName
, c_parent.name as ParentColumnName
, t_child.name as ReferencedTableName
, c_child.name as ReferencedColumnName
from sys.foreign_keys fk
inner join sys.foreign_key_columns fkc on fkc.constraint_object_id = fk.object_id
inner join sys.tables t_parent on t_parent.object_id = fk.parent_object_id
inner join sys.columns c_parent on fkc.parent_column_id = c_parent.column_id
and c_parent.object_id = t_parent.object_id
inner join sys.tables t_child on t_child.object_id = fk.referenced_object_id
inner join sys.columns c_child on c_child.object_id = t_child.object_id
and fkc.referenced_column_id = c_child.column_id
order by t_parent.name, c_parent.name

Execute Dynamically Selected Query in SQL

I am using a Multi tenant Shared schema database, so i have so many schema,
Required:
I want to remove some schema; for that i have to remove all the CONSTRAINT of tables in that schema to delete a table. I got the the list of query to remove all the CONSTRAINT of a schema and the query to delete the tables from below code
Question:
From the below code i got a list of Queries,now i am copy that queries and executing that list of queries manually,can i do that automatically ?
Code
SET NOCOUNT ON;
DECLARE #SchemaName nvarchar(250)
SET #SchemaName='schemaname1'
--Step 1: Remove all CONSTRAINT
SELECT 'ALTER TABLE ' +'[' + s.name + '].[' + t.name + ']' +' DROP CONSTRAINT [' + f.name +']'
FROM sys.foreign_keys f
INNER JOIN sys.TABLES t ON f.parent_object_id=t.object_id
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
WHERE t.is_ms_shipped=0
and t.schema_id = schema_id(#SchemaName);
--Step 2: Drop all Tables
SELECT 'DROP TABLE ' + '[' + s.name + '].[' + t.name + ']'
FROM sys.TABLES t
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
WHERE t.is_ms_shipped=0 and t.schema_id = schema_id(#SchemaName);
Using COALESCE function we can turn multiple rows into a single string in SQL Server
Following code is working fine, to delete All the table in a Schema
SELECT * INTO #mytemp FROM INFORMATION_SCHEMA.SCHEMATA
WHERE [SCHEMA_NAME] in ('schemaname1','schemaname2','schemaname3')
WHILE (SELECT Count(*) FROM #mytemp) > 0
BEGIN
DECLARE #SCHEMA_NAME varchar(100)
SELECT #SCHEMA_NAME = [SCHEMA_NAME] FROM #mytemp
DECLARE #SQL VARCHAR(MAX)
SET #SQL='';
--Step 1: Remove all CONSTRAINT
SELECT #SQL= COALESCE(#SQL,'') +'ALTER TABLE ' +'[' + s.name + '].[' + t.name + ']' +' DROP CONSTRAINT [' + f.name +']'+ ' ; '
FROM sys.foreign_keys f
INNER JOIN sys.TABLES t ON f.parent_object_id=t.object_id
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
WHERE t.is_ms_shipped=0
and t.schema_id = schema_id(#SCHEMA_NAME);
--Step 2: Drop all Tables
SELECT #SQL= COALESCE(#SQL,'')+'DROP TABLE ' + '[' + s.name + '].[' + t.name + ']'+ ' ; '
FROM sys.TABLES t
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
WHERE t.is_ms_shipped=0 and t.schema_id = schema_id(#SCHEMA_NAME);
EXEC(#SQL)
--Custom Query End
DELETE #mytemp WHERE [SCHEMA_NAME] = #SCHEMA_NAME
END
DROP TABLE #mytemp

How do I get constraints on a SQL Server table column

I have a column called MealType (VARCHAR) in my table with a CHECK constraint for {"Veg", "NonVeg", "Vegan"}
That'll take care of insertion.
I'd like to display these options for selection, but I couldn't figure out the SQL query to find out the constraints of a particular column in a table.
From a first glance at system tables in SQL Server, it seems like I'll need to use SQL Server's API to get the info. I was hoping for a SQL query itself to get it.
Easiest and quickest way is to use:
sp_help 'TableName'
This query should show you all the constraints on a table:
select chk.definition
from sys.check_constraints chk
inner join sys.columns col
on chk.parent_object_id = col.object_id
inner join sys.tables st
on chk.parent_object_id = st.object_id
where
st.name = 'Tablename'
and col.column_id = chk.parent_column_id
can replace the select statement with this:
select substring(chk.Definition,2,3),substring(chk.Definition,9,6),substring(chk.Definition,20,5)
SELECT obj_table.NAME AS 'table',
columns.NAME AS 'column',
obj_Constraint.NAME AS 'constraint',
obj_Constraint.type AS 'type'
FROM sys.objects obj_table
JOIN sys.objects obj_Constraint
ON obj_table.object_id = obj_Constraint.parent_object_id
JOIN sys.sysconstraints constraints
ON constraints.constid = obj_Constraint.object_id
JOIN sys.columns columns
ON columns.object_id = obj_table.object_id
AND columns.column_id = constraints.colid
WHERE obj_table.NAME='table_name'
ORDER BY 'table'
You can use
sp_helpconstraint 'tableName', 'nomsg'
to get all the constraints for the table.
"sp_help" return far more information.
Thanks to orgtrigger for his example!
I improved it to be able to remove unnecessary constraints (and then create their modified versions, if needed). Maybe this code will be useful for anybody.
-- removing old constraints
DECLARE #ConstraintNames TABLE (Name VARCHAR(MAX), RowNum INT)
DECLARE #TableName VARCHAR(100) = 'HubSpot'
INSERT #ConstraintNames
SELECT [constraint].name,
ROW_NUMBER() OVER (ORDER BY [constraint].[name]) AS RowNum
FROM sys.default_constraints [constraint]
INNER JOIN sys.columns col
ON [constraint].parent_object_id = col.object_id
INNER JOIN sys.tables st
ON [constraint].parent_object_id = st.object_id
WHERE
st.name = #TableName
AND col.name IN ('ForceUpdateOnImport', 'ForceUpdateOnExport')
AND col.column_id = [constraint].parent_column_id
SELECT * FROM #ConstraintNames
DECLARE #i INT = 1,
#count INT,
#constraintName VARCHAR(MAX),
#sql VARCHAR(MAX)
SELECT #count = COUNT(1) FROM #ConstraintNames
WHILE #i <= #count
BEGIN
SELECT #constraintName = cn.Name FROM #ConstraintNames cn WHERE cn.RowNum = #i
SET #sql = 'ALTER TABLE ' + #TableName + ' DROP CONSTRAINT ' + #constraintName
EXEC (#sql)
SET #i = #i + 1
END
Below is helpful for check and default constraints. I use it for implicit constraints to offer up guidance for what the name should be. If you remove everything after the where clause, it should be good for any check/default constraints.
SELECT /* obj_table.NAME AS 'table',
columns.NAME AS 'column',
obj_Constraint.NAME AS 'constraint',
obj_Constraint.type AS 'type',
sss.name as 'schema',*/
'ALTER TABLE [' + ltrim(rtrim(sss.name))+'].['+ltrim(rtrim(obj_table.name)) + '] DROP CONSTRAINT [' + obj_Constraint.NAME + '];' As 'Wrong_Implicit_Constraint',
'ALTER TABLE [' + ltrim(rtrim(sss.name))+'].['+ltrim(rtrim(obj_table.name)) + '] ADD CONSTRAINT [' + CASE obj_Constraint.type
WHEN 'D' THEN 'DF' WHEN 'F' THEN 'FK'
WHEN 'U' THEN 'UX' WHEN 'PK' THEN 'PK' WHEN 'N' THEN 'NN' WHEN 'C' THEN 'CK'
END + '_' + ltrim(rtrim(obj_table.name)) + '_' + columns.NAME + ']' +
CASE obj_Constraint.type WHEN 'D' THEN ' DEFAULT (' + dc.definition +') FOR [' + columns.NAME + ']'
WHEN 'C' THEN ' CHECK (' + cc.definition +')'
ELSE '' END +
';' As 'Right_Explicit_Constraint'
FROM sys.objects obj_table
JOIN sys.objects obj_Constraint ON obj_table.object_id = obj_Constraint.parent_object_id
JOIN sys.sysconstraints constraints ON constraints.constid = obj_Constraint.object_id
JOIN sys.columns columns ON columns.object_id = obj_table.object_id
AND columns.column_id = constraints.colid
left join sys.schemas sss on obj_Constraint.schema_id=sss.schema_id
left join sys.default_constraints dc on dc.object_id = obj_Constraint.object_id
left join sys.check_constraints cc on cc.object_id = obj_Constraint.object_id
WHERE obj_Constraint.type_desc LIKE '%CONSTRAINT'
AND RIGHT(obj_Constraint.name,10) LIKE '[_][_]________' --match double underscore + 8 chars of anything
AND RIGHT(obj_Constraint.name,8) LIKE '%[A-Z]%' --Ensure alpha in last 8
AND RIGHT(obj_Constraint.name,8) LIKE '%[0-9]%' --Ensure numeric in last 8
AND RIGHT(obj_Constraint.name,8) not LIKE '%[^0-9A-Z]%' --Ensure no special chars

SQL how do you query for tables that refer to a specific foreign key value?

I have table A with a primary key on column ID and tables B,C,D... that have 1 or more columns with foreign key relationships to A.ID.
How do I write a query that shows me all tables that contain a specific value (eg 17) of the primary key?
I would like to have generic sql code that can take a table name and primary key value and display all tables that reference that specific value via a foreign key.
The result should be a list of table names.
I am using MS SQL 2012.
You want to look at sys.foreignkeys. I would start from http://blog.sqlauthority.com/2009/02/26/sql-server-2008-find-relationship-of-foreign-key-and-primary-key-using-t-sql-find-tables-with-foreign-key-constraint-in-database/
to give something like
declare #value nvarchar(20) = '1'
SELECT
'select * from '
+ QUOTENAME( SCHEMA_NAME(f.SCHEMA_ID))
+ '.'
+ quotename( OBJECT_NAME(f.parent_object_id) )
+ ' where '
+ COL_NAME(fc.parent_object_id,fc.parent_column_id)
+ ' = '
+ #value
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
Not an ideal one, but should return what is needed (list of tables):
declare #tableName sysname, #value sql_variant
set #tableName = 'A'
set #value = 17
declare #sql nvarchar(max)
create table #Value (Value sql_variant)
insert into #Value values (#value)
create table #Tables (Name sysname, [Column] sysname)
create index IX_Tables_Name on #Tables (Name)
set #sql = 'declare #value sql_variant
select #value = Value from #Value
'
set #sql = #sql + replace((
select
'insert into #Tables (Name, [Column])
select ''' + quotename(S.name) + '.' + quotename(T.name) + ''', ''' + quotename(FC.name) + '''
where exists (select 1 from ' + quotename(S.name) + '.' + quotename(T.name) + ' where ' + quotename(FC.name) + ' = #value)
'
from
sys.columns C
join sys.foreign_key_columns FKC on FKC.referenced_column_id = C.column_id and FKC.referenced_object_id = C.object_id
join sys.columns FC on FC.object_id = FKC.parent_object_id and FC.column_id = FKC.parent_column_id
join sys.tables T on T.object_id = FKC.parent_object_id
join sys.schemas S on S.schema_id = T.schema_id
where
C.object_id = object_id(#tableName)
and C.name = 'ID'
order by S.name, T.name
for xml path('')), '
', CHAR(13))
--print #sql
exec(#sql)
select distinct Name
from #Tables
order by Name
drop table #Value
drop table #Tables
You could achive that by writing some SQL. I post an example but it is just a mockup showing the way you could do it.
CREATE TABLE tempTable
(
TABLE_NAME varchar(255)
);
CREATE UNIQUE CLUSTERED INDEX Idx_tempTable ON tempTable(TABLE_NAME);
DECLARE #var2 nvarchar(max)
INSERT INTO tempTable
SELECT DISTINCT
TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%COLUMN_NAME%'
/*FOREACH result of the tempTable you could find if the COLUMN_NAME of the result(table) has the value you want*/
SET #var2 = 'SELECT TABLE_NAME FROM ' + tempTableResult + ' WHERE COLUMN_NAME=VALUE'
exec(#var2)
DROP TABLE tempTable
The query will return a list of table names and append those names with the data (if used to find), or a "(no date)" if child data are held as daily instances.
Also, apologies up front for the use of a cursor. I tend to use them only for special cases such as this one (i.e. finding the few odd records that may exist across 100's of tables).
In my case, a table references just under 400 tables (all of which are generated automatically as part of a "learning" system), and depending on the type of entry saved, data may or may not written into these tables. A further twist is some of these data are also by-date, so the query must also check for the existence of a date column in each table with the foreign key (fortunately, in these instances the column will always be named "dt").
From the nearly 400 tables listed as referencing the "asset" table. Only a dozen tables actually held data for the particular entry I was investigating. All of the tables held the data as daily instances/detail.
The referenced table's name is "asset" and the Dynamic SQL includes a sub query (convert a human readable name to a primary key, used as a FK value).
The cursor query is from Gishu at How can I list all foreign keys referencing a given table in SQL Server?
DECLARE #TableName varchar(255)
DECLARE #FKeyColumn varchar(255)
DECLARE #rowcount int
DECLARE #sqlCMD NVARCHAR(500)
DECLARE #dt NVARCHAR(10) = '2008-08-25'
DECLARE #SymbolName NVARCHAR(9) = 'thingImLookingFor'
DECLARE #byDate varchar(255)
DECLARE TableCursor
CURSOR FOR select
t.name as TableWithForeignKey,
c.name as ForeignKeyColumn
from sys.foreign_key_columns as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where
fk.referenced_object_id = (select object_id from sys.tables where name = 'asset')
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO #TableName, #FKeyColumn
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sqlCMD = 'SELECT #rowcount=count(*) FROM ' + #TableName + ' WHERE ' + #FKeyColumn + '=(SELECT asset_id FROM asset WHERE primary_symbol=''' + #SymbolName + ''')'
SET #byDate = ' (no date)'
IF EXISTS(SELECT 1 FROM sys.columns
WHERE sys.columns.name = N'dt'
AND sys.columns.object_id = Object_ID(#TableName))
BEGIN
SET #sqlCMD = #sqlCMD + ' AND dt=''' + #dt + ''''
SET #byDate = ' (' + #dt + ')'
END
EXEC sp_executesql #sqlCMD, N'#rowcount int output', #rowcount output
IF(#rowcount=1) PRINT(#TableName + #byDate)
FETCH NEXT FROM TableCursor INTO #TableName, #FKeyColumn
END
CLOSE TableCursor;
DEALLOCATE TableCursor;

How to drop SQL default constraint without knowing its name?

In Microsoft SQL Server, I know the query to check if a default constraint exists for a column and drop a default constraint is:
IF EXISTS(SELECT * FROM sysconstraints
WHERE id=OBJECT_ID('SomeTable')
AND COL_NAME(id,colid)='ColName'
AND OBJECTPROPERTY(constid, 'IsDefaultCnst')=1)
ALTER TABLE SomeTable DROP CONSTRAINT DF_SomeTable_ColName
But due to typo in previous versions of the database, the name of the constraint could be DF_SomeTable_ColName or DF_SmoeTable_ColName.
How can I delete the default constraint without any SQL errors? Default constraint names don't show up in INFORMATION_SCHEMA table, which makes things a bit trickier.
So, something like 'delete the default constraint in this table/column', or 'delete DF_SmoeTable_ColName', but don't give any errors if it can't find it.
Expanding on Mitch Wheat's code, the following script will generate the command to drop the constraint and dynamically execute it.
declare #schema_name nvarchar(256)
declare #table_name nvarchar(256)
declare #col_name nvarchar(256)
declare #Command nvarchar(1000)
set #schema_name = N'MySchema'
set #table_name = N'Department'
set #col_name = N'ModifiedDate'
select #Command = 'ALTER TABLE ' + #schema_name + '.[' + #table_name + '] DROP CONSTRAINT ' + d.name
from sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
where t.name = #table_name
and t.schema_id = schema_id(#schema_name)
and c.name = #col_name
--print #Command
execute (#Command)
Rob Farley's blog post might be of help:
Two ways to find / drop a default constraint without knowing its name
Something like:
declare #table_name nvarchar(256)
declare #col_name nvarchar(256)
set #table_name = N'Department'
set #col_name = N'ModifiedDate'
select t.name, c.name, d.name, d.definition
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = #table_name
and c.name = #col_name
I found that this works and uses no joins:
DECLARE #ObjectName NVARCHAR(100)
SELECT #ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
WHERE [object_id] = OBJECT_ID('[tableSchema].[tableName]') AND [name] = 'columnName';
EXEC('ALTER TABLE [tableSchema].[tableName] DROP CONSTRAINT ' + #ObjectName)
Just make sure that columnName does not have brackets around it because the query is looking for an exact match and will return nothing if it is [columnName].
To drop constraint for multiple columns:
declare #table_name nvarchar(256)
declare #Command nvarchar(max) = ''
set #table_name = N'ATableName'
select #Command = #Command + 'ALTER TABLE ' + #table_name + ' drop constraint ' + d.name + CHAR(10)+ CHAR(13)
from sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where t.name = #table_name and c.name in ('column1','column2','column3')
--print #Command
execute (#Command)
Expanded solution (takes table schema into account):
-- Drop default contstraint for SchemaName.TableName.ColumnName
DECLARE #schema_name NVARCHAR(256)
DECLARE #table_name NVARCHAR(256)
DECLARE #col_name NVARCHAR(256)
DECLARE #Command NVARCHAR(1000)
set #schema_name = N'SchemaName'
set #table_name = N'TableName'
set #col_name = N'ColumnName'
SELECT #Command = 'ALTER TABLE [' + #schema_name + '].[' + #table_name + '] DROP CONSTRAINT ' + d.name
FROM sys.tables t
JOIN sys.default_constraints d
ON d.parent_object_id = t.object_id
JOIN sys.schemas s
ON s.schema_id = t.schema_id
JOIN sys.columns c
ON c.object_id = t.object_id
AND c.column_id = d.parent_column_id
WHERE t.name = #table_name
AND s.name = #schema_name
AND c.name = #col_name
EXECUTE (#Command)
Run this command to browse all constraints:
exec sp_helpconstraint 'mytable' --and look under constraint_name.
It will look something like this: DF__Mytable__Column__[ABC123]. Then you can just drop the constraint.
Drop all default contstraints in a database - safe for nvarchar(max) threshold.
/* WARNING: THE SAMPLE BELOW; DROPS ALL THE DEFAULT CONSTRAINTS IN A DATABASE */
/* MAY 03, 2013 - BY WISEROOT */
declare #table_name nvarchar(128)
declare #column_name nvarchar(128)
declare #df_name nvarchar(128)
declare #cmd nvarchar(128)
declare table_names cursor for
SELECT t.name TableName, c.name ColumnName
FROM sys.columns c INNER JOIN
sys.tables t ON c.object_id = t.object_id INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id
ORDER BY T.name, c.name
open table_names
fetch next from table_names into #table_name , #column_name
while ##fetch_status = 0
BEGIN
if exists (SELECT top(1) d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = #table_name and c.name = #column_name)
BEGIN
SET #df_name = (SELECT top(1) d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = #table_name and c.name = #column_name)
select #cmd = 'ALTER TABLE [' + #table_name + '] DROP CONSTRAINT [' + #df_name + ']'
print #cmd
EXEC sp_executeSQL #cmd;
END
fetch next from table_names into #table_name , #column_name
END
close table_names
deallocate table_names
I hope this could be helpful for whom has similar problem .
In ObjectExplorer window, select your database=> Tables,=> your table=> Constraints. If the customer is defined on create column time, you can see the default name of constraint including the column name.
then use:
ALTER TABLE yourTableName DROP CONSTRAINT DF__YourTa__NewCo__47127295;
(the constraint name is just an example)
Following solution will drop specific default constraint of a column from the table
Declare #Const NVARCHAR(256)
SET #Const = (
SELECT TOP 1 'ALTER TABLE' + YOUR TABLE NAME +' DROP CONSTRAINT '+name
FROM Sys.default_constraints A
JOIN sysconstraints B on A.parent_object_id = B.id
WHERE id = OBJECT_ID('YOUR TABLE NAME')
AND COL_NAME(id, colid)='COLUMN NAME'
AND OBJECTPROPERTY(constid,'IsDefaultCnst')=1
)
EXEC (#Const)
declare #ery nvarchar(max)
declare #tab nvarchar(max) = 'myTable'
declare #qu nvarchar(max) = 'alter table '+#tab+' drop constraint '
select #ery = (select bj.name from sys.tables as tb
inner join sys.objects as bj
on tb.object_id = bj.parent_object_id
where tb.name = #tab and bj.type = 'PK')
exec(#qu+#ery)
Take a look.
I had some columns that had multiple default constraints created, so I create the following stored procedure:
CREATE PROCEDURE [dbo].[RemoveDefaultConstraints] #table_name nvarchar(256), #column_name nvarchar(256)
AS
BEGIN
DECLARE #ObjectName NVARCHAR(100)
START: --Start of loop
SELECT
#ObjectName = OBJECT_NAME([default_object_id])
FROM
SYS.COLUMNS
WHERE
[object_id] = OBJECT_ID(#table_name)
AND [name] = #column_name;
-- Don't drop the constraint unless it exists
IF #ObjectName IS NOT NULL
BEGIN
EXEC ('ALTER TABLE '+#table_name+' DROP CONSTRAINT ' + #ObjectName)
GOTO START; --Used to loop in case of multiple default constraints
END
END
GO
-- How to run the stored proc. This removes the default constraint(s) for the enabled column on the User table.
EXEC [dbo].[RemoveDefaultConstraints] N'[dbo].[User]', N'enabled'
GO
-- If you hate the proc, just get rid of it
DROP PROCEDURE [dbo].[RemoveDefaultConstraints]
GO
Useful for some columns that had multiple default constraints or check constraints created:
Modified https://stackoverflow.com/a/16359095/206730 script
Note: this script is for sys.check_constraints
declare #table_name nvarchar(128)
declare #column_name nvarchar(128)
declare #constraint_name nvarchar(128)
declare #constraint_definition nvarchar(512)
declare #df_name nvarchar(128)
declare #cmd nvarchar(128)
PRINT 'DROP CONSTRAINT [Roles2016.UsersCRM].Estado'
declare constraints cursor for
select t.name TableName, c.name ColumnName, d.name ConstraintName, d.definition ConstraintDefinition
from sys.tables t
join sys.check_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where t.name = N'Roles2016.UsersCRM' and c.name = N'Estado'
open constraints
fetch next from constraints into #table_name , #column_name, #constraint_name, #constraint_definition
while ##fetch_status = 0
BEGIN
print 'CONSTRAINT: ' + #constraint_name
select #cmd = 'ALTER TABLE [' + #table_name + '] DROP CONSTRAINT [' + #constraint_name + ']'
print #cmd
EXEC sp_executeSQL #cmd;
fetch next from constraints into #table_name , #column_name, #constraint_name, #constraint_definition
END
close constraints
deallocate constraints
Always generate script and review before you run. Below the script
select 'Alter table dbo.' + t.name + ' drop constraint '+ d.name
from sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where c.name in ('VersionEffectiveDate','VersionEndDate','VersionReasonDesc')
order by t.name
declare #table_name nvarchar(100)
declare #col_name nvarchar(100)
declare #constraint nvarchar(100)
set #table_name = N'TableName'
set #col_name = N'ColumnName'
IF EXISTS (select c.*
from sys.columns c
inner join sys.tables t on t.object_id = c.object_id
where t.name = #table_name
and c.name = #col_name)
BEGIN
select #constraint=d.name
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = #table_name
and c.name = #col_name
IF LEN(ISNULL(#constraint, '')) <> 0
BEGIN
DECLARE #sqlcmd VARCHAR(MAX)
SET #sqlcmd = 'ALTER TABLE ' + QUOTENAME(#table_name) + ' DROP CONSTRAINT' +
QUOTENAME(#constraint);
EXEC (#sqlcmd);
END
END
GO
This will check if the foreign key exists or not. If it exists, then drop that.
DECLARE #SCHEMA_NAME NVARCHAR(256)
-- The table name you what drop the foreign key from.
DECLARE #ALTER_TABLE_NAME NVARCHAR(256)
-- The table name is liked with the foreign key.
DECLARE #REF_TABLE_NAME NVARCHAR(256)
DECLARE #COMMAND NVARCHAR(MAX)
SET #SCHEMA_NAME = N'MySchema';
SET #ALTER_TABLE_NAME = N'MyAlterTable';
SET #REF_TABLE_NAME = N'MyReferTable';
IF EXISTS (
SELECT NAME
FROM SYS.FOREIGN_KEYS
WHERE PARENT_OBJECT_ID = (
SELECT OBJECT_ID
FROM SYS.OBJECTS
WHERE OBJECT_ID = OBJECT_ID(#ALTER_TABLE_NAME)
)
AND REFERENCED_OBJECT_ID = (
SELECT OBJECT_ID
FROM SYS.OBJECTS
WHERE OBJECT_ID = OBJECT_ID(#REF_TABLE_NAME)
)
)
BEGIN
SELECT #COMMAND = 'ALTER TABLE ['
+ #SCHEMA_NAME
+ '].['
+ #ALTER_TABLE_NAME
+ '] DROP CONSTRAINT '
+ NAME
FROM SYS.FOREIGN_KEYS
WHERE PARENT_OBJECT_ID = (
SELECT OBJECT_ID
FROM SYS.OBJECTS
WHERE OBJECT_ID = OBJECT_ID(#ALTER_TABLE_NAME)
)
AND REFERENCED_OBJECT_ID = (
SELECT OBJECT_ID
FROM SYS.OBJECTS
WHERE OBJECT_ID = OBJECT_ID(#REF_TABLE_NAME)
)
EXECUTE (#COMMAND)
END
GO
Here is a simple solution, just replace your_table and the column_name.
DECLARE #var0 nvarchar(128)
SELECT #var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'${default_schema}.your_table')
AND col_name(parent_object_id, parent_column_id) = 'column_name';
IF #var0 IS NOT NULL
EXECUTE ('ALTER TABLE ${default_schema}.your_table DROP CONSTRAINT [' + #var0 + ']');
GO