且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

sql server 如何在有多个选项的更新语句中选择值?

更新时间:2023-02-02 23:42:28

它将所有的结果设置为数据.查询后最终得到哪一个取决于返回结果的顺序(最后设置哪一个).

It sets all of the results to the Data. Which one you end up with after the query depends on the order of the results returned (which one it sets last).

由于没有 ORDER BY 子句,您可以使用 Sql Server 提出的任何顺序.这通常遵循磁盘上记录的物理顺序,并且通常遵循表的聚集索引.但是这个顺序并不是一成不变的,尤其是在涉及连接时.如果连接匹配具有非聚集索引的索引的列,则它很可能会根据该索引对结果进行排序.最后,除非你给它一个 ORDER BY 子句,否则 Sql Server 会按照它认为最快的顺序返回结果.

Since there's no ORDER BY clause, you're left with whatever order Sql Server comes up with. That will normally follow the physical order of the records on disk, and that in turn typically follows the clustered index for a table. But this order isn't set in stone, particularly when joins are involved. If a join matches on a column with an index other than the clustered index, it may well order the results based on that index instead. In the end, unless you give it an ORDER BY clause, Sql Server will return the results in whatever order it thinks it can do fastest.

您可以通过将 upate 查询转换为选择查询来玩这个,这样您就可以看到结果.请注意,对于目标表的每条记录,源表中哪条记录最先出现,哪条记录最后出现.将其与更新查询的结果进行比较.然后再次使用索引并再次检查结果以查看结果.

You can play with this by turning your upate query into a select query, so you can see the results. Notice which record comes first and which record comes last in the source table for each record of the destination table. Compare that with the results of your update query. Then play with your indexes again and check the results once more to see what you get.

当然,这里可能很棘手,因为 UPDATE 语句不允许使用 ORDER BY 子句,因此无论您找到什么,您都应该真正编写连接,使其与目标表 1:1 匹配.您可能会发现 APPLY 运算符对实现此目标很有用,您可以使用它来有效地连接到另一个表并保证连接仅匹配一条记录.

Of course, it can be tricky here because UPDATE statements are not allowed to use an ORDER BY clause, so regardless of what you find, you should really write the join so it matches the destination table 1:1. You may find the APPLY operator useful in achieving this goal, and you can use it to effectively JOIN to another table and guarantee the join only matches one record.