PB 将游标中的数据存到数组中
以一个案例做说明,从数据表user_account中取出要接收短信的电话号码,并将其存储在数组中。
该数据表的结构如下:
account | name | password | using_id | accept | phone_code |
ZS | 张三 | 123 | 1 | 0 | 18833336666 |
LS | 李四 | 123 | 1 | 1 | 18912345678 |
WW | 王五 | 123 | 0 | 1 | 13112345678 |
ZL | 赵六 | 123 | 1 | 1 | 13612345678 |
PK | 皮 | 123 | 1 | 1 | 18888888888 |
直接上正确的代码,然后再解释:
string ls_phone_code[],tel //接收短信的手机号码 int i=1 //PB数组下标从1开始 connect; declare cur_phone_code cursor for select user_account.phone_code from user_account where user_account.accept = '1' and user_account.using_id = '1' and user_account.phone_code is not NULL using sqlca; open cur_phone_code; if sqlca.SQLCode <> 0 then close cur_phone_code; return end if
//open后,先fetch一次 fetch cur_phone_code into :tel; do while sqlca.SQLCode = 0 ls_phone_code[i] = tel fetch cur_phone_code into :tel; i++ loop close cur_phone_code; disconnect;
最终,数组ls_phone_code将被正确赋值:
ls_phone_code[1]=18912345678
ls_phone_code[2]=13612345678
ls_phone_code[3]=18888888888
前面都没什么问题,红色加粗代码块是唯一可能出错的地方。
的确,我就是在这里出错了。下面上一下之前错误的代码,做个对比:
// open后,直接循环
do while sqlca.SQLCode = 0 fetch cur_phone_code into :ls_phone_code[i] ; i++ loop
赋值结果:
ls_phone_code[1]=18912345678
ls_phone_code[2]=13612345678
ls_phone_code[3]=18888888888
ls_phone_code[4]=NULL
两个结果做一对此基本就能找到问题所在:错误的代码多fetch了一次,最后一次没有取到值,所以向数组中写入一个NULL值,第四次循环结束后,SQLCode才变成100
为什么多fetch了一次呢?
原因就在:打开游标后SQLCode的值为open操作的结果,而非fetch的。
这和我的上篇随笔 SQL Server 系统表使用举例 中的第一个示例其实是一样一样的~