/****** Needed for writing of DI changes in database (e.g. deleting an existing DI) because in MSSQL, I can't drop a column if there's still a constraint using it******/
SET ANSI_NULLS ON
GO
  CREATE PROCEDURE DropColumnWithConstraints
	@tableName varchar(128),
	@columnName varchar(128)
	AS SET NOCOUNT ON
	SET xact_abort ON
	WHILE 0=0 BEGIN
		DECLARE @defaultName varchar(128)
		SET @defaultName = (
		SELECT TOP 1 defaults.Name
			FROM sys.tables tab
			INNER JOIN sys.default_constraints defaults ON tab.object_id = defaults.parent_object_id
			INNER JOIN sys.columns col ON defaults.parent_object_id = col.object_id AND col.column_id = defaults.parent_column_id
			WHERE tab.Name = @tableName AND col.Name = @columnName)
		IF @defaultName IS NULL BREAK
		EXEC ('ALTER TABLE "'+@tableName+'" DROP CONSTRAINT "'+@defaultName+'"')
	END
	WHILE 0=0 BEGIN
		DECLARE @constraintName varchar(128)
		SET @constraintName = (
		SELECT TOP 1 CONSTRAINT_NAME
			FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
			WHERE TABLE_NAME = @tableName AND COLUMN_NAME = @columnName)
		IF @constraintName IS NULL BREAK
		EXEC ('ALTER TABLE "'+@tableName+'" DROP CONSTRAINT "'+@constraintName+'"')
	END
	EXEC ('ALTER TABLE "'+@tableName+'" DROP COLUMN "'+@columnName+'"')
GO
