Skip to content

Instantly share code, notes, and snippets.

@m4tt1mus
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m4tt1mus/30476a4b1e889292131e to your computer and use it in GitHub Desktop.
Save m4tt1mus/30476a4b1e889292131e to your computer and use it in GitHub Desktop.
-- Adapted from Jon Galloway: http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
-- This couldn't handle multiple schemas in the same table. Fixed.
-- Removed concat to widen support to earlier versions of MSSQL.
CREATE PROCEDURE [dbo].[sp_drop_constraints]
@database [sysname] = NULL,
@table [sysname],
@verbose [bit] = 0
AS
BEGIN
IF @database IS NULL
BEGIN
SET @database = DB_NAME();
END
DECLARE @crlf [varchar](max) = CHAR(13) + CHAR(10);
DECLARE @sql [nvarchar](max);
WHILE EXISTS
(
SELECT *
FROM [INFORMATION_SCHEMA].[TABLE_CONSTRAINTS]
WHERE [CONSTRAINT_CATALOG] = @database
AND [TABLE_NAME] = @table
AND [CONSTRAINT_TYPE] != 'PRIMARY KEY'
)
BEGIN
SELECT @sql = 'ALTER TABLE [' + @database + '].[' + CONSTRAINT_SCHEMA + '].[' + TABLE_NAME + ']' + @crlf +
'DROP CONSTRAINT [' + REPLACE([CONSTRAINT_NAME], ']', ']]') + ']' + @crlf
FROM [INFORMATION_SCHEMA].[TABLE_CONSTRAINTS]
WHERE [CONSTRAINT_CATALOG] = @database
AND [TABLE_NAME] = @table
AND [CONSTRAINT_TYPE] != 'PRIMARY KEY';
IF @verbose = 1
BEGIN
PRINT @sql;
PRINT '';
END
EXEC [sys].[sp_executesql] @sql
END
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment