Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Change auto-named SQL constraint
-- Table: Users
-- Column: Age
-- Constraint: auto-generated, e.g. DF__Users__Age__<random>
-- Find a specific constrait name assuming there is a single constraint only
DECLARE @ConstraintName nvarchar(100)
SELECT @ConstraintName = FROM sys.default_constraints c
INNER JOIN sys.columns col ON col.default_object_id = c.object_id
WHERE c.parent_object_id = OBJECT_ID('dbo.Users') AND = 'Age'
-- Drop the constraint if found
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE [dbo].[Users] DROP CONSTRAINT ' + @ConstraintName)
-- Add a new constraint with a predefined name
ALTER TABLE [dbo].[Users] ADD DEFAULT ((0)) FOR [Age]
-- Blog post:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.