优化 Last-auto-inc 值的查询
Sybase Advantage数据库
我正在做一个查询,
INSERT INTO nametable
SELECT * FROM nametable WHERE [indexkey]=32;
UPDATE nametable Set FieldName=1
WHERE [IndexKey]=(SELECT max([indexKey]) FROM nametable);
目的是将给定的记录复制到新记录中,然后用一些新值更新新创建的记录。 “indexKey”被声明为 autoinc 并且是表的主键。
我不确定这是否可以在单个语句中以更快的速度实现,或者;;;建议表示赞赏。
Sybase Advantage Database
I am doing a query
INSERT INTO nametable
SELECT * FROM nametable WHERE [indexkey]=32;
UPDATE nametable Set FieldName=1
WHERE [IndexKey]=(SELECT max([indexKey]) FROM nametable);
The purpose is to copy a given record into a new record, and then update the newly created record with some new values. The "indexKey" is declared as autoinc and is the primary key to the table.
I am not sure if this can be achieved in a single statement with better speed or;;; suggestions appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它可以通过单个语句来实现,但它会使代码更容易受到架构更改的影响。假设除了 FieldName 和 indexKey 列之外,表中还有 2 个附加列。那么下面的语句就可以达到你的目的了。
但是,如果表结构发生变化,则该语句将需要相应更新。
顺便说一句,您原来的实现在多用户场景中并不安全。 UPDATE 语句中的 max( [indexKey] ) 可能不是 INSERT 语句生成的 max( [indexKey] ) 。另一个用户可能在两个语句之间插入了另一行。要使用原始方法,您应该使用 LastAutoInc() 标量。
It can be achieved with a single statement but it will make the code more susceptible to schema changes. Suppose that there are 2 additional columns in the table besides the FieldName and the indexKey columns. Then the following statement will achieve your objective.
However, if the table structure changes, this statement will need to be updated accordingly.
BTW, your original implementation is not safe in multi-user scenarios. The max( [indexKey] ) in the UPDATE statement may not be the one generated by the INSERT statement. Another user could have inserted another row between the two statements. To use your original approach, you should use the LastAutoInc() scalar.