Skip to content

Instantly share code, notes, and snippets.

@rmorenobello
Last active June 23, 2022 18:40
Show Gist options
  • Save rmorenobello/8ac05379e4e5b3c3c21ef113929381d6 to your computer and use it in GitHub Desktop.
Save rmorenobello/8ac05379e4e5b3c3c21ef113929381d6 to your computer and use it in GitHub Desktop.
SQL Server - General
https://www.mssqltips.com/sql-server-tip-category/52/sql-server-management-studio/
http://dbadailystuff.com/2012/10/14/remove-identity-property-from-a-primary-key-column-in-sql-server
USE [INSTANCE]
GO
SET NOCOUNT ON;
BEGIN TRANSACTION
BEGIN TRY
-- Adding a new temporary column
ALTER TABLE [INSTANCE].[dbo].[NotifEntidad]
ADD [new_EntidadId] INT NULL;
-- Updating the new column with the values sorted as we want
EXEC sp_executesql N'UPDATE [INSTANCE].[dbo].[NotifEntidad] SET [new_EntidadId] = [EntidadId]'
-- Setting the new column as NOT NULL
ALTER TABLE [INSTANCE].[dbo].[NotifEntidad]
ALTER COLUMN [new_EntidadId] INT NOT NULL;
-- Disable Foreign Keys Constraints
ALTER TABLE [INSTANCE].[dbo].[LU_DemandaEntidad]
DROP CONSTRAINT FK_LU_DemandaEntidad_NotifEntidad;
-- Drop Primary Key
ALTER TABLE [INSTANCE].[dbo].[NotifEntidad]
DROP CONSTRAINT [PK_NotifEntidad]
-- Drop IDENTITY column
ALTER TABLE [INSTANCE].[dbo].[NotifEntidad]
DROP COLUMN [EntidadId]
-- Rename column ID_EXENCION_NEW --> ID_EXENCION
EXEC sp_rename '[dbo].[NotifEntidad].new_EntidadId', 'EntidadId', 'COLUMN';
-- Add new Primary Key
ALTER TABLE [INSTANCE].[dbo].[NotifEntidad]
ADD CONSTRAINT [PK_NotifEntidad] PRIMARY KEY CLUSTERED ( [EntidadId] ASC )
-- Enable constraints (without rechecking them)
ALTER TABLE [INSTANCE].[dbo].[LU_DemandaEntidad]
WITH NOCHECK DROP CONSTRAINT FK_LU_DemandaEntidad_NotifEntidad
FOREIGN KEY (EntidadId)
REFERENCES [INSTANCE].dbo.NotifEntidad(EntidadId);
PRINT 'IDENTITY removed successfully from NotifEntidad'
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
PRINT 'ERROR:' + ERROR_MESSAGE()
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
SET NOCOUNT ON;
BEGIN TRANSACTION
BEGIN TRY
(...DDL and DML SENTENCES like ALTERS, etc., EXEC 'UPDATE...', etc....)
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
PRINT 'ERROR:' + ERROR_MESSAGE()
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment