Skip to content

Instantly share code, notes, and snippets.

@ststeiger
Created September 8, 2015 13:22
Show Gist options
  • Select an option

  • Save ststeiger/69b4e07dbc006da36933 to your computer and use it in GitHub Desktop.

Select an option

Save ststeiger/69b4e07dbc006da36933 to your computer and use it in GitHub Desktop.
Recreate certain constraints with delete CASCADE
SELECT
'
IF EXISTS(
SELECT rc.*
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS rc
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU1
ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE KCU1.TABLE_NAME = ''' + REPLACE(FK_TABLE_NAME, '''', '''''') + '''
AND rc.CONSTRAINT_NAME = ''' + REPLACE(FK_CONSTRAINT_NAME, '''', '''''') + '''
AND rc.CONSTRAINT_SCHEMA = ''dbo''
)
ALTER TABLE "dbo"."' + REPLACE(FK_TABLE_NAME, '''', '''''') + '" DROP CONSTRAINT "' + REPLACE(FK_CONSTRAINT_NAME, '''', '''''') + '"
GO
ALTER TABLE "dbo"."' + REPLACE(FK_TABLE_NAME, '''', '''''') + '" WITH NOCHECK
ADD CONSTRAINT "' + REPLACE(FK_CONSTRAINT_NAME, '''', '''''') + '" FOREIGN KEY("' + REPLACE(FK_COLUMN_NAME, '''', '''''') + '")
REFERENCES "dbo"."' + REPLACE(REFERENCED_TABLE_NAME, '''', '''''') + '" ("' + REPLACE(REFERENCED_COLUMN_NAME, '''', '''''') + '")
ON DELETE CASCADE
GO
ALTER TABLE "dbo"."' + REPLACE(FK_TABLE_NAME, '''', '''''') + '" CHECK CONSTRAINT "' + REPLACE(FK_CONSTRAINT_NAME, '''', '''''') + '"
GO
' AS cmd
FROM V_DELDATA_ForeignKeyRelations
WHERE (1=1)
-- AND FK_TABLE_NAME = 'T_SYS_Aussenobjektrechte'
AND FK_COLUMN_NAME LIKE '%_GRANTEE_ID'
ORDER BY FK_TABLE_NAME, FK_COLUMN_NAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment