使用来自另一个表中的 SELECT 的 UPDATE 语句覆盖 ID 值 SQL Server 2008
我有两个表,其中正好有 20 行。我想用 Table1 中的 ID 值覆盖 Table2 的 ID 值,以便我可以使用 JOIN 查询进行测试。我将如何覆盖这些值?
我找到了指导如何使用 SELECT 语句进行 UPDATE 的帖子,但是它需要将数据连接到列上,在我的情况下没有列匹配。
UPDATE Table2
SET Table2.ID = Table1.ID
FROM Table1
上面的查询使用 Table1 中第一个 ID 列的值覆盖 Table2 中的所有 ID 列。
I have two tables that have exactly 20 rows in them. I want to overwrite Table2's ID values with the ID values from Table1 so that I can do tests with JOIN queries. How would I go about overwriting the values?
I have found posts instructing how to do an UPDATE using a SELECT statement, however it requires the data to be joined on a column, in my case no columns match.
UPDATE Table2
SET Table2.ID = Table1.ID
FROM Table1
The query above overwrites all ID columns in Table2 with the value of the first ID column in Table1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了好玩(是的,周五晚上我有一种扭曲的幽默感!),这里有一个查询可以做到这一点! - 我已经声明了表和顶部,并且每个表中只使用了 6 行,但您会得到这样的想法:
更新:
基于 @sllev 建议的替代更新命令:
For fun (yes I have a warped sense of humour for a Friday night!), here is a query that does it! - I've declare the tables and the top and only used 6 rows in each table, but you'll get the idea:
Update:
Alternative Update command based on suggestion by @sllev:
还有另一个解决方案,这次使用 CTE。表
#First
从表#Second
获取id:And another solution, this time using CTE's. Table
#First
gets the id's from table#Second
:由于其中只有 20 行,因此我将通过输入您的更改来手动执行更新。特别是因为这些记录并不像通常通过选择进行更新时那样相互关联。
Since you only have 20 rows in them, I would manually perform the update by typing in your changes. Especially since the records do not correlate to each other as they typically should for an update with a select.
正如评论中所述,如果这是一次性测试,则仅测试 20 行的最简单选项是在 SSMS 中打开 Table2 并输入 ID 值。
As stated in the comments, if this is a one-off for testing the easiest option for just 20 rows would be to open Table2 in SSMS and type the ID values in.