I have an existing table, A, defined as follows:
CREATE TABLE dbo.A(
id int IDENTITY(1, 1) NOT NULL PRIMARY KEY CLUSTERED,
name nvarchar(255) NOT NULL UNIQUE NONCLUSTERED
);
This table has 1,000s of existing records.
I now require a new table, B, defined as follows:
CREATE TABLE dbo.B(
id int IDENTITY(1, 1) NOT NULL PRIMARY KEY CLUSTERED,
some_value int NOT NULL
);
I need to create a record in B for each record in A and add a reference from the A record to the corresponding B record. Firstly, I need to add a new field to table A that references table B (which necessarily must be nullable with a default value of NULL, at this stage):
ALTER TABLE dbo.A
ADD b_id int NULL references dbo.B;
How can I create the necessary B records and update the A.b_id field accordingly? I'm looking for something like this:
UPDATE dbo.A
SET b_id = (INSERT INTO dbo.B(some_value) VALUES(5));
such that the value of b_id is the id field of the newly inserted B. (Clearly, this query isn't valid.)
The only solution I can come up with is to write a complex stored procedure using multiple, separate queries. Is there a way to do this with a single query?