Я должен денормализовать существующую таблицу и сохранить все данные, которые уже есть.
Ранее моя структура таблиц была
TABLE A:
[id] INT IDENTITY(1,1)
[name] NVARCHAR(100)
[countryID] INT
TABLE B:
[id] INT IDENTITY(1,1)
[countryName] NVARCHAR(100)
Новая структура TableA:
TABLE A:
[id] INT IDENTITY(1,1)
[name] NVARCHAR(100)
[countryName] NVARCHAR(100)
Интересно, есть ли более элегантное решение, чем это
--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