用于两次更新和搜索查询的高效 SQL 查询
我有一个这样的查询:
SELECT TOP 1 ID, DATA, OTHERINF FROM MYTABLE WHERE DATE = @DATE
在读取行数据并使用它之后,我想更新检索到的行并更改其中的一列(在另一个事务中)。
但正如你在这里看到的,我搜索了该行两次。有什么方法可以让我记住该行并进行更新而无需再次搜索。
谢谢。
I have a query like this:
SELECT TOP 1 ID, DATA, OTHERINF FROM MYTABLE WHERE DATE = @DATE
and after reading the row data and using it I want to update that retrieved row and change one of it's columns (in another transaction).
But as you see here i searched for that row twice. Is there any way that I keep remember the row and do the update without searching again.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在第一个查询中,您检索了 id。在第二个查询中,使用它来查找要更新的行,而不是使用日期:
In the first query you retrieved the id. In the second query use that to find the row to update instead of using the date:
我知道它已经过时了,但您也可以对光标进行定位更新
例如
I know its out of vogue but you can also do positioned updates on cursors
e.g.
这应该可以做到
This should do it
您可以将 UPDATE 与 SELECT 合并到一个语句中,但不能跨两个事务。因此,如果您需要更新另一个事务中的值而不是您选择的事务(我不清楚其原因),则需要两个语句。
You can combine the UPDATE with the SELECT into one statement, but not across two transactions. Therefore, if you need to update the value in another transaction than you select it (the reason for this is unclear to me), you need two statements.
我认为 DATE 列没有索引(如果没有,为什么没有?)那么,您最好的选择是确保检索主键(不是那个 ID 吗?),然后将其用作您的条件更新。
I presume that the DATE column isn't indexed (if not, why not?) Your best bet, then, is to make sure you retrieve the primary key (isn't that ID?) and then use that as your condition in the update.