我相信我需要一个游标for循环来遍历表test_data中的street1列。我有一个程序需要测试表中的每一行。
这是我到目前为止所做的:
cursor c1 is
street1
from test_data
Begin
If Instr(street1, ‘Cnr’, 1) >= 1;
Then
Newstreetname := Substr(street1, Instr(street1, ‘Cnr’, 1)+3);
Else if
Instr(street1, ‘PO Box’, 1) >= 1;
Then
Newstreetname:= Substr(street1, Instr(street1, ‘PO Box’, 1));
Else if
REGEXP_ Instr (street1, [\d], 1) = 0;
Then
Newstreetname:= street1;
Else if
REGEXP_ Instr (street1, [\d], 1) >= 1;
Then
Newstreetnumber:= regexp_substr(street1, '\d+(\s|\/)(\d+)?-?(\d+)?(\w {1})?');
Newstreetname:= regexp_substr(street1, '(\w+\s\w+)$');
End
答案 0 :(得分:9)
* 1。在游标定义中需要SELECT和分号
* 2。您可以在光标上添加FOR LOOP
例如:
DECLARE
cursor c1 is
SELECT street1
from test_data;
r1 c1%ROWTYPE;
BEGIN
FOR r1 IN c1 LOOP
... do your stuff with r1.street1
END LOOP;
END;
您也可以完全避免使用显式游标定义,例如:
FOR r1 IN (SELECT street1 FROM test_data) LOOP
... do your stuff with r1.street1
END LOOP;
* 3。您的IF语句不能包含分号 - 例如:
If
Instr(r1.street1, 'Cnr', 1) >= 1
Then
* 4。 [edit]因此您要更新表格,列newstreetnumber
和newstreetname
- 在这种情况下,您可以执行以下操作:
DECLARE
cursor c1 is
SELECT street1
from test_data
FOR UPDATE;
r1 c1%ROWTYPE;
BEGIN
FOR r1 IN c1 LOOP
... do your stuff with r1.street1
UPDATE test_data
SET newstreetnumber = ...
,newstreetname = ...
WHERE CURRENT OF c1;
END LOOP;
END;
但请注意,这对于大卷来说效果不佳,我宁愿在一个UPDATE语句中完成所有操作。
答案 1 :(得分:2)
正如Jeffrey Kemp所说,这可以在一个更新状态中完成:
UPDATE test_data
SET newstreetname = CASE WHEN Instr(street1, ‘Cnr’, 1) >= 1
THEN Substr(street1, Instr(street1, ‘Cnr’, 1)+3)
WHEN Instr(street1, ‘PO Box’, 1) >= 1
THEN Substr(street1, Instr(street1, ‘PO Box’, 1))
WHEN REGEXP_Instr (street1, '[\d]', 1) = 0
THEN street1
WHEN REGEXP_Instr (street1, '[\d]', 1) >= 1
THEN regexp_substr(street1, '(\w+\s\w+)$')
END,
newstreetnumber = CASE WHEN .....
END;