Skip to content

Instantly share code, notes, and snippets.

@qlawmarq
Created May 26, 2022 06:52
Show Gist options
  • Save qlawmarq/b626223a7543fcc6e2b3cea5e1a34851 to your computer and use it in GitHub Desktop.
Save qlawmarq/b626223a7543fcc6e2b3cea5e1a34851 to your computer and use it in GitHub Desktop.
Delete/drop columns with foreign key constraints or default values constraints in SQL server.
-- Search default value constraints:
SELECT
obj.name
FROM
sys.objects AS obj
JOIN
sys.columns AS clm ON obj.object_id = clm.default_object_id
WHERE
obj.type = 'D' AND obj.parent_object_id = OBJECT_ID('User') AND clm.name = 'CompanyId';
-- Search foreign key constraints:
SELECT
fs.name AS 'Foreign Key',
s.name + '.' + t.name AS 'Table Name'
FROM
sys.foreign_keys fs
INNER JOIN sys.tables t
ON t.object_id = fs.parent_object_id
INNER JOIN sys.schemas s
ON s.schema_id = t.schema_id;
-- Drop constraints and Drop column:
ALTER TABLE User DROP CONSTRAINT DF__User__HasCr__12B12345;
ALTER TABLE User DROP COLUMN CompanyId;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment