Created
May 26, 2022 06:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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