[英]How to select first row and update it in IBM DB2 9.7
可以使用通用表表達式在T-SQL中完成魔術,但是如何在DB2 9.7中完成呢?
1. select the first row in a table
2. Update that specific row
這兩個步驟必須在一個事務中執行。 請幫忙 :)
不需要CTE,也不需要游標! 只需定義將返回全選行的查詢,然后在其上運行更新:
UPDATE (
SELECT *
FROM schema.table
WHERE thing1 = 'blah'
AND thing2 = 'something'
ORDER BY key
FETCH FIRST ROW ONLY
)
SET thing3 = 'updated'
在DB2 Linux / Unix / Windows 9.7上測試
在游標上進行迭代時,可以在DB2中使用類似的方法。
這是一個例子:
begin
declare at_end sqlstate;
declare name anchor emp.name;
declare continue handler for not found
set at_end = TRUE;
declare c cursor for
select tabname from emp
for update;
open c;
fetch c into name;
if at_end <> TRUE then
update emp
set name = 'foo'
where current of c;
end if;
end@
此代碼將僅更新從選擇返回的第一行。
這將在發出select語句時創建一個意圖更新鎖,然后將其轉換為update語句中的排他鎖。 一旦選擇完成,這使得其他事務無法修改該行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.