Skip to content

Instantly share code, notes, and snippets.

@osya
Created March 19, 2015 08:57
Show Gist options
  • Save osya/18ee92aa27197f69bc38 to your computer and use it in GitHub Desktop.
Save osya/18ee92aa27197f69bc38 to your computer and use it in GitHub Desktop.
Foreign key #SQL
Check If Primary Key exists:
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_NAME = 'SAT_Lands_Open_Source'
AND TABLE_SCHEMA ='rlt')
ALTER TABLE [rlt].[SAT_Lands_Open_Source] DROP CONSTRAINT [PK_Realty_Lands_Open_Source]
SQL server will not let you truncate the table while the constraint exists, even if it's disabled. Drop the constraint and re-create it after truncating the table. Or just drop and re-create the tables, whichever is easier to do in your application.
IF EXISTS (SELECT *
FROM sys.foreign_keys
WHERE object_id = OBJECT_ID( N'FK_ETL_PACKAGE_ETL_LOADERS')
AND parent_object_id = OBJECT_ID( N'[cfg].[ETL_PACKAGE]')
)
ALTER TABLE [cfg] .[ETL_PACKAGE] DROP CONSTRAINT [FK_ETL_PACKAGE_ETL_LOADERS]
GO
truncate table [cfg]. [ETL_LOADERS]
truncate table [cfg]. [ETL_PACKAGE]
GO
--Add Foreign key back
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE cfg. ETL_LOADERS SET (LOCK_ESCALATION = TABLE )
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE cfg. ETL_PACKAGE ADD CONSTRAINT
FK_ETL_PACKAGE_ETL_LOADERS FOREIGN KEY
(
Loader_Code
) REFERENCES cfg. ETL_LOADERS
(
Loader_Code
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE cfg. ETL_PACKAGE SET (LOCK_ESCALATION = TABLE )
GO
COMMIT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment