简体   繁体   中英

Inserting values from another table into a column where values are null

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM