我正在使用 SQL Server 2005 中的数据库,它在我需要它们的所有表中都没有唯一 ID。我的解决方法是创建另一组具有强制唯一 ID 的有点相似的表。
我现在想将新 ID 的引用带回初始表集以用于连接等目的。 (另外:这些表会被定期截断并重新填充,因此有解决方法)。
换句话说:我想在 Table2 中获取 ID,并与 Table1 中的记录正确关联。
对我来说困难的部分是 Table1 中的记录只有在考虑三个字段时才是唯一的。
我在表 1 中添加了一个 ID 字段,然后我尝试了以下操作:
UPDATE dbo.Table1
SET dbo.Table1.ID = dbo.Table2.ID
WHERE dbo.Table1.foo = dbo.Table2.foo
And dbo.Table1.bar = dbo.Table2.bar
And dbo.Table1.buzz = dbo.Table2.buzz
但是,我得到以下类型的错误:
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "dbo.Table2.foo" could not be bound.
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "dbo.Table2.bar" could not be bound.
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "dbo.Table2.buzz" could not be bound.
有什么想法吗?
谢谢。
最佳答案
这应该适合你:
UPDATE t
SET id = t2.id
FROM table1 t JOIN
table2 t2 ON t.foo = t2.foo AND
t.bar = t2.bar AND
t.buzz = t2.buzz
关于sql - 在特定条件下将一个表中的字段设置为另一个表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15045876/