Home > Software design >  Inserting values from another table into a column where values are null
Inserting values from another table into a column where values are null

Time:05-06

I have a table A with ID's only and another table B with two columns, ID and Product Number. The ID column in table B has nulls and Product Number has Product Numbers. I would like to update table B with the ID's in column in no specific order just so that the Product Number has ID's.

I have tried to use update but that has not worked, have tried insert but it just adds the ID's in A to the bottom of the list in B. Would like to do this in Microsoft SQL.

SQL code tried:

IF OBJECT_ID('tempdb..#ProductNum') IS NOT NULL DROP TABLE #ProductNum

SELECT  ID
INTO    #ProductNum
FROM    Products

    

UPDATE  [ProductCatalogue] PC
SET
PC.ID = Pn.ID
FROM #ProductNum Pn
INNER JOIN 
[ProductCatalogue] PC   
ON Pc.ID = Pn.ID
WHERE Pc.ID IS NULL

CodePudding user response:

It sounds a lot like you would be better off having the ID-Column Autoincrement, instead of giving it the IDs from table A. This is already explained in this answer.

In case you actually need the specific IDs from table A, this SO thread might help you.

CodePudding user response:

Solved the issue by creating auto increment columns on each table and called it Row_ID. Then i used Row_ID to join the tables together with some logic provided by Chris above.

  • Related