Search code examples
sqlsql-serverdenormalization

Table denormalization


I have to denormalize existing table and save all the data that is already there. Previously my tables structure was

TABLE A:
[id] INT IDENTITY(1,1)
[name] NVARCHAR(100)
[countryID] INT

TABLE B:
[id] INT IDENTITY(1,1)
[countryName] NVARCHAR(100)

New TableA structure:

TABLE A:
[id] INT IDENTITY(1,1)
[name] NVARCHAR(100)
[countryName] NVARCHAR(100)

I wonder if there is more elegant solution than this one

--BACKUP TABLE TO VARIABLE
DECLARE @backup TABLE (
            [Id] INT NOT NULL,
            [Name] NVARCHAR (1000) NOT NULL,
            [CountryId] INT NULL,
INSERT INTO @backup SELECT * FROM [dbName].[TableA]

--RECREATE THE TABLE WITH NEW STRUCTURE
DROP TABLE [dbName].[TableA]
CREATE TABLE [dbName].[TableA]
        (
            [Id] INT IDENTITY(1, 1) NOT NULL,
            [Name] NVARCHAR (1000) NOT NULL,
            [CountryId] NVARCHAR (100) NULL,
            CONSTRAINT [PK_TableA] PRIMARY KEY CLUSTERED 
            (
                [Id] ASC
            ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

SET IDENTITY_INSERT [dbName].[TableA] ON --Required to save original Id's

--INSERT DATA FROM BACKUP TABLE
INSERT INTO [dbName].[TableA]([Id],[Name],[CountryId])
SELECT 
backup.[Id],
backup.[Name],
[dbName].[TableB].[Name],
FROM @backup backup
LEFT JOIN [dbName].[TableB] on backup.[CountyId] = [dbName].[TableB].[Id]

SET IDENTITY_INSERT [dbName].[TableA] ON

Solution

  • Different people may have different choice. But for me, I will chose this steps to do the same-

    1. BACKUP Table-A
    2. Alter Table-A and add new column "countryName"
    3. Update data in countryName column by left joining with Table-B
    4. Alter Table-A to DROP column "countryID"
    5. DROP Table-B (Based on Requirement)

    Note: I would chose Alter Table-A option just to avoid Restore of table in case of data lose.