Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SELECT INSERT INTO Generate Unique Id

I'm attempting to select a table of data and insert this data into another file with similar column names (it's essentially duplicate data). Current syntax as follows:

INSERT INTO TABLE1 (id, id2, col1, col2)
SELECT similiarId, similiarId2, similiarCol1, similiarCol2  
FROM TABLE2

The problem I have is generating unique key fields (declared as integers) for the newly inserted records. I can't use table2's key's as table1 has existing data and will error on duplicate key values.

I cannot change the table schema and these are custom id columns not generated automatically by the DB.

like image 703
jrb Avatar asked Jun 18 '12 18:06

jrb


People also ask

How do I get a random unique ID in SQL?

SQL Reference GuideThe function random_uuid returns a randomly generated UUID, as a string of 36 characters. This function can be used to generate values for columns of type UUID in an INSERT or UPDATE SQL statements. In this example, a randomly generated UUID is fetched using the random_uuid function.

How do I add a unique ID?

Use the NEWID() function to obtain a globally unique ID (GUID). INSERT INTO THAI_MK_MT_Log(GUID, Status) VALUES (newid(), 'S'). newid() function will generate an unique identifier each time. INSERT INTO THAI_MK_MT_Log(GUID, Status) VALUES (cast ('xxxxxxxx ....

What is Newid in SQL?

The following example uses NEWID() to assign a value to a variable declared as the uniqueidentifier data type. The value of the uniqueidentifier data type variable is printed before the value is tested. Here is the result set. The value returned by NEWID is different for each computer.

How do I create a new GUID in SQL?

-- If you want to generate a new Guid (uniqueidentifier) in SQL server the you can simply use the NEWID() function. -- This will return a new random uniqueidentifier e.g. You can directly use this with INSERT statement to insert new row in table.


2 Answers

Does table1 have an auto-increment on its id field? If so, can you lose similiarId from the insert and let the auto-increment take care of unique keys?

INSERT INTO TABLE1 (id2, col1, col2) SELECT similiarId2, similiarCol1, similiarCol2
FROM TABLE2
like image 189
alex stacey Avatar answered Oct 12 '22 11:10

alex stacey


As per you requirement you need to do you query like this:

INSERT INTO TABLE1 (id, id2, col1, col2)
SELECT (ROW_NUMBER( ) OVER ( ORDER BY ID ASC )) 
+ (SELECT MAX(id) FROM TABLE1) AS similiarId
, similiarId2, similiarCol1, similiarCol2  
FROM TABLE2

What have I done here:
Added ROW_NUMBER() which will start from 1 so also added MAX() function for ID of destination table.

For better explanation See this SQLFiddle.

like image 27
Himanshu Jansari Avatar answered Oct 12 '22 10:10

Himanshu Jansari