I have a table like this:
CREATE Table tblClassProperty (
ClassPropertyID integer IDENTITY(1,1) PRIMARY KEY,
Active bit DEFAULT 0 NOT NULL,
DEL bit DEFAULT 0 NOT NULL,
FINAL bit DEFAULT 0 NOT NULL,
Locked bit DEFAULT 0 NOT NULL,
_Project integer FOREIGN KEY REFERENCES tblProject(ProjectID),
_Property integer FOREIGN KEY REFERENCES tblProperty(PropertyID),
_Class integer FOREIGN KEY REFERENCES tblClass(ClassID)
CONSTRAINT CClassProperty UNIQUE(_Project,_Property,_Class))
I am migrating data from an old table (in another DB) into this one. For the most of the columns I am just copying the data from the other table. The foreign key columns don’t exist in the old DB, they are just random values linked with the corresponding tables in the new DB. For your solution please take it for granted that the values for the columns _Project, _Property and _Class need to be generated the way they are now (with the SELECT TOP 1 ...)
INSERT INTO ClassDB..tblClassProperty (Active, DEL, FINAL, Locked,
_Project, _Property, _Class)
SELECT Active, DEL, FINAL, Locked,
(SELECT TOP 1 ProjectID FROM ClassDB..tblProject ORDER BY NEWID()),
(SELECT TOP 1 PropertyID FROM ClassDB..tblProperty ORDER BY NEWID()),
(SELECT TOP 1 ClassID FROM ClassDB..tblClass ORDER BY NEWID()),
FROM ClassDB_Access..tblClassProperty
Now, the INSERT INTO script won’t run because of the unique constraint, and the constraint must stay as it is.
My question: I need a script that copies the existing columns, generates the foreign keys as above, BUT the generated values for the tuple (_Project, _Property, _Class) will be unique as per constraint.
The script has to run in SQL Server 2008 R2, and in the future also in Oracle.
You might cross join all three columns, assign random row numbers to them and join them back to tblClassproperty augmented by row_number:
This will not work in Oracle without reshuffling cte parts – or you might rewrite this using derived tables for instant compatibility.
Disclaimer: Other than syntax check this is not tested. Performance might be awful.
Edit: Forgot to mention that, in case of duplicate values in
IDs, you might want to do distinct before cross joins.