3.6. 关于语句写法 语句的效率与SQL 语句的写法有很大关系。在几种写法中选择一个合适的写法相当重要,有时效率会急剧提高。因此,在效率有问题的地方多检查自己语句的写法,有可能会取得重大突破。以下是一些实例: (1).在保单表中查找“003”险种的“0101”区站的数据 select * from rta1 where bm_cert[1,7]=”0030101” 该语句运行前设置set explain on,运行后查看sqexplain.out 结果如下: QUERY: select * from rta1 where bm_cert[1,7]="0030107" Estimated Cost: 1 Estimated # of Rows Returned: 1 1) hsx.rta1: INDEX PATH 8 (1) Index Keys: bm_cert Lower Index Filter: hsx.rta1.bm_cert[1,7] = '0030107' 显示的搜索路径为索引路径,但实际上效率很低。现改为如下写法: select * from rta1 where bm_cert > = ”00301010000000000000” and bm_cert<=”00301019999999999999” 该语句运行前设置set explain on,运行后查看sqexplain.out 结果如下: QUERY: select * from rta1 where bm_cert >= "003010100000000" and bm_cert<=”00301019999999999999” Estimated Cost: 1 Estimated # of Rows Returned: 3 1) hsx.rta1: INDEX PATH (1) Index Keys: bm_cert Lower Index Filter: hsx.rta1.bm_cert >= '003010100000000' 显示与第一个写法无明显差别,实际上第二种写法效率远远高于第一种。实际测试第一种写法的时间需要2 分41 秒而第二种写法的执行时间只需14 秒。
因此, 程序中最好不要使用bm_cert[x,y]=”???” 这种形式, 而改为 bm_cert>=”???” 这种形式。 (2). 在程序中,我们经常做这样的工作,先判断表内是否有该条数据,如果有就 update 该条数据,否则就插入一条。一般都写成如下形式: select .. from . where key=t_key if status=notfound then insert into .. else update .. end if 实际上,写成如下形式效率更高 update . where key=t_key if status=0 and sqlca.sqlerrd[3]=0 then insert into .. end if 因为当该条数据存在时,只做一次写操作。 (3). 在应用系统中有这样一条SQL 语句。 select print_name from validate_item where (acc_book_type = t_acc_book_type and acc_book_code = t_acc_book_code and (center_code = t_center_code or center_code=”000000”) and item_code = t_item_code and direction_idx = t_dir_idx_val1 and direction_other = t_dir_oth_val1) ( validate_item 表中acc_book_type , acc_book_code , center_code , item_code , direction_idx , direction_other 为唯一索引) 该语句的效率不高,改写为以下形式后效率得到了很大提高。在存储过程中,上面的写法此存储过程执行需用时1 分多钟,改为下面的写法后,用 时仅需1 秒. select print_name into t_str from validate_item where (acc_book_type = t_acc_book_type and acc_book_code = t_acc_book_code and center_code = t_center_code and item_code = t_item_code and direction_idx = t_dir_idx_val1 and direction_other = t_dir_oth_val1) or (acc_book_type = t_acc_book_type
[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] 下一页
|