I have tables [Moulds], [Machines] and [SpareParts] each with different attributes/columns. I would like to make them into subtypes and create a supertype table for them called [Assets] so I can reference all of them together in a maintenance scheduling application.
The [Assets] table will simply contain columns [Asset_ID], [Asset_Type] and [Description]. [Asset_ID] is an identity PK, [Asset_Type] is an int (eg. Moulds = 1, Machines = 2, etc.) and [Description] will be taken from the subtype tables. I will add a column called [Asset_FK] to each of the subtype tables as a foreign key.
My problem is that each subtype table has hundreds to thousands of rows of data already in them. It would be unreasonable to manually create PK-FK for each existing record, but I'm uncertain of the SQL required to automate it.
For populating the [Assets] table, I currently have this:
DECLARE @AssetID TABLE (ID int)
INSERT INTO Assets (Assets.Description, Assets.Asset_Type)
OUTPUT Inserted.Asset_ID INTO @AssetID
SELECT IsNull(Moulds.Description,''), 5
FROM Moulds
But, I'm not sure how to update the FK in [Moulds] in the same query, or if this is even the right approach. Specifically, I'm not sure how to identify the row in subtypes I selected which I want to update.
To summarize my question, I have a blank supertype table and filled subtype tables. I want to populate the supertype table using the subtype tables and automatically fill in the FK values for the existing subtype records to link them. How can I do this using SQL (MS SQL Server 2008r2)?
So, based on rs.'s answer, I came up with an idea. I add a temporary column to table [Assets] that stores the PK of table [Moulds] (or some other subtype table), use it for the update operations, then drop the column. It looks like this:
USE [Maintenance]
ALTER TABLE Assets
ADD Asset_FK int null
GO
DECLARE @AssetID TABLE (ID int)
INSERT INTO Assets (Description, Asset_Type, Asset_FK)
OUTPUT Inserted.Asset_ID INTO @AssetID
SELECT IsNull(Description,''), 5, Mould_PK
FROM Moulds
UPDATE m
SET m.Asset_ID = a.Asset_ID
FROM Moulds m
INNER JOIN Assets a
ON m.Mould_PK = a.Asset_FK AND a.Asset_Type = 5
INNER JOIN @AssetID a2 ON a.Asset_ID = a2.ID
GO
ALTER TABLE Assets
DROP COLUMN Asset_FK
Probably not the most elegant answer, but it seems simple and works.