Schema Change: Convert field to foreign key on a different table
I currently have a table like this:
Stuff ---------- StuffId identity int not null Description nvarchar(4000) null ...
I want to store the Description in a separate table that I have set aside specifically for user-generated content:
Content ---------- ContentId identity int not null Content nvarchar(max) not null ...
(this table already exists, and other tables already reference entries in it.)
So I need to:
- Create a DescriptionContentId field on the Stuff table with a foreign key constraint.
- Copy the current Description content into the Content table.
- Set each DescriptionContentId to have the ContentId value that was automatically generated when inserting values in step 2.
- Drop the Description column.
I know how to do steps 1 and 4, but steps 2 and 3 are eluding me, because they need to be done pretty much simultaneous开发者_如何转开发ly. This seems like it would be a fairly common schema change. What's the best way to do it?
Update
I'm a step closer thanks to the Output keyword, but I'm still missing something. Here's what I'd like to do:
create table #tmp (StuffId int, ContentId int)
insert into Content(Content)
output s.StuffId, inserted.ContentId
into #tmp(StuffId, ContentId)
select Description
from Stuff s
where Description IS NOT NULL
But I can't reference s.StuffId because it isn't one of the fields inserted into the Content table. How can I correlate the ID of the Stuff with the ID of the Content as I'm inserting a new Content item for each Stuff entry?
The output clause will come to your rescue.
It will output the description and the identity column from the insert into a table varaible and then you can use that data to update the other table.
If description is not unique, you may have to do the following: add a column for the stuffID column to the content table. Then output the stuffid and content id from the insert, update the table using the stuffid to ensure uniqueness, Drop the stuffid column from the content table.
an example from Books Online as to how to use the OUTPUT
DECLARE @MyTableVar table(
LastName nvarchar(20) NOT NULL,
FirstName nvarchar(20) NOT NULL,
CurrentSales money NOT NULL
);
INSERT INTO dbo.EmployeeSales (LastName, FirstName, CurrentSales)
OUTPUT INSERTED.LastName,
INSERTED.FirstName,
INSERTED.CurrentSales
INTO @MyTableVar
SELECT c.LastName, c.FirstName, sp.SalesYTD
FROM HumanResources.Employee AS e
INNER JOIN Sales.SalesPerson AS sp
ON e.EmployeeID = sp.SalesPersonID
INNER JOIN Person.Contact AS c
ON e.ContactID = c.ContactID
WHERE e.EmployeeID LIKE '2%'
ORDER BY c.LastName, c.FirstName;
精彩评论