SQL 服务器:设置行 ID 相同的值

SQL Server : set value where row id is same

我正在使用 SQL 服务器,但我遇到了问题。我有两个表,table1table2

Table1 有一个列 VALUEtable2 有两个列 IdWiegand_Id

我想要做的是将列的 VALUE(在 table1 中)设置为 Wiegand_Id 的值,其中它们的 ID 相同。

我会在下面给你一些这些表格的截图,这样你就可以明白我想做什么了。

Here's table1

Here's table2

And here's all the tables, including the last one which is the updated table2

我试过下面这个查询,

UPDATE [table2]
SET value = (SELECT [table1].[wiegand id]
             FROM [table1]
             WHERE [table2].[value] = [table1].[id])

但它显示错误:

Cannot insert the value NULL into column 'VALUE', table 'table2'; column does not allow nulls. UPDATE fails.

尽管两个表中都没有空值。

如果有人能告诉我我做错了什么以及我应该对此查询进行哪些更改才能使其正常工作,我们将不胜感激。

谢谢。

您可以使用 JOINAPPLY :

update t2
     set t2.value = t1.[wiegand id]
from table2 t2 inner join
     table1 t1
     on t1.id = t2.value;

APPLY 版本应为:

update t2
     set t2.value = t1.[wiegand id]
from table2 t2 cross apply
     (select top (1) t1.[wiegand id]
      from table1 t1
      where t1.id = t2.value
     ) t1;

对于此查询:

UPDATE [table2]
SET value = (SELECT [table1].[wiegand id]
             FROM [table1]
             WHERE [table2].[value] = [table1].[id]
            )

会执行LEFT OUTER JOIN这样,错误就很明显了。但是,您的数据表明没有错误。因此,我建议通过 INNER JOINs 更新 table 以避免错误。

UPDATE [table2]
SET [table2].value = [table1].[wiegand id]
FROM [table1]
INNER JOIN [table2] ON [table1].[wiegand id] = [table2].value