I am changing the database schema and migrating data that was originally stored in one table to two tables.
Old schema:
CREATE TABLE [dbo].[X](
[Id] TINYINT NOT NULL PRIMARY KEY,
[SomeData] VARBINARY(MAX) NULL,
)
New schema:
CREATE TABLE [dbo].[X](
[Id] TINYINT NOT NULL PRIMARY KEY,
[SomeDataId] BIGINT,
)
CREATE TABLE [dbo].[SomeData](
[Id] BIGINT NOT NULL PRIMARY KEY IDENTITY,
[Binary] VARBINARY(MAX) NOT NULL
)
I know the steps are:
- Create the new column [SomeDataId] on [X]
- Copy data from [X].[SomeData] to [SomeData].[Binary]
- Remove column [SomeData] on [X]
I am having issue on how to complete step 2 in T-SQL only. I know I can:
- Use
SCOPE_IDENTITY()
to get the inserted identity seed - Use
OUTPUT INSERTED.Id
to get the inserted identity seed - Use
INSERT INTO ... SELECT ... FROM
to copy data from one table to another
However I cannot figure out how to update the relevant row on [X] with the identity seed just inserted, without using some kind of for-loop logic which sounds silly.
SomeDataId
defined as aBIGINT
when tableX
can have no more than 256 rows? And why do you even need a new id column when you can useX (Id)
?SomeData
holds data for a lot of tables. I discovered thatX
,Y
,Z
etc. in my database has SomeData, and I want to move them to a central table.