简体   繁体   English

将另一个表中的值插入到值为 null 的列中

[英]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.我有一个只有 ID 的表 A,另一个表 B 有两列,ID 和产品编号。 The ID column in table B has nulls and Product Number has Product Numbers.表 B 中的 ID 列有空值,产品编号有产品编号。 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.我想以没有特定顺序的列中的 ID 更新表 B,以便产品编号具有 ID。

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.我试过使用更新但没有用,试过插入但它只是将 A 中的 ID 添加到 B 中列表的底部。想在 Microsoft SQL 中执行此操作。

SQL code tried: SQL 密码试过:

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.听起来你最好使用 ID 列自动增量,而不是从表 A 中给它 ID。这已经在这个答案中解释过了。

In case you actually need the specific IDs from table A, this SO thread might help you.如果您确实需要表 A 中的特定 ID, SO 线程可能会对您有所帮助。

Solved the issue by creating auto increment columns on each table and called it Row_ID .通过在每个表上创建自动递增列并将其命名为Row_ID解决了这个问题。 Then I used Row_ID to join the tables together with some logic provided by @Chris above.然后我使用Row_ID将表与上面@Chris 提供的一些逻辑连接在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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