數據庫應用程序通常進行一項確定的工作,在編寫和編譯時就可以確定完整的SQL語句,但是當需要使用PowerBuilder不支持的嵌入SQL語句,或者在編譯時不能確定SQL語句的具體格式和參數時,只能在程序運行過程中構造SQL語句,需要使用動態SQL語句。
以Format 4 動態SQL語句為例,使用格式如下:
DECLARE Cursor | Procedure
DYNAMIC CURSOR | PROCEDURE
FOR DynamicStagingArea ;
PREPARE DynamicStagingArea FROM SQLStatement
{USING TransactionObject} ;
DESCRIBE DynamicStagingArea
INTO DynamicDescriptionArea ;
OPEN DYNAMIC Cursor | Procedure
USING DESCRIPTOR DynamicDescriptionArea} ;
EXECUTE DYNAMIC Cursor | Procedure
USING DESCRIPTOR DynamicDescriptionArea ;
FETCH Cursor | Procedure
USING DESCRIPTOR DynamicDescriptionArea ;
CLOSE Cursor | Procedure ;
在使用動態SQL語句時,需準備DynamicStagingArea對象(全局對象SQLSA)和DynamicDescriptionArea對象(全局對象SQLDA)。定義游標或過程,讀取PREPARE語句中的SQL語句以及語句中說明的參數和類型,執行FETCH語句后,調用相關的函數逐條讀取并處理檢索結果。
動態SQL語句雖然解能夠在程序運行過程中構造SQL語句,但在實際應用中較少使用。若SELECT語句的結果序列一定,可以通過重新指定DataWindow對象的SELECT語句的方法,達到動態修改SQL語句的功能。運用時首先用Describe函數讀取DataWindow對象的SELECT語句,用Replace等函數修改出符合要求的SELECT語句,并且可以增加檢索條件,再用SetSQLSelect函數為DataWindow控件指定修改后的SELECT語句。
程序代碼:
string sql_string,sql_new
long start_pos=1
string old_str //select語句中需要替換的字符串
string new_str //替換字符串,可以是結構相同的表名
dw_1.settransobject(sqlca)
sql_string=dw_1.Describe("DataWindow.Table.Select")
// Find the first oclearcase/" target="_blank" >ccurrence of old_str.
start_pos = Pos(sql_string, old_str, start_pos)
// Only enter the loop if you find old_str.
DO WHILE start_pos > 0
// Replace old_str with new_str.
sql_string = Replace(sql_string, start_pos, &
Len(old_str), new_str)
// Find the next occurrence of old_str.
start_pos = Pos(sql_string, old_str, &
start_pos+Len(new_str))
LOOP
sql_new=sql_string+" where ……" //增加where字句
//判斷setsqlselect 函數調用是否成功 ,不成功則返回
if (dw_1.setsqlselect(sql_new)=-1) then
messagebox("錯誤","不能修改SQL語句!",Exclamation!)
return
end if
dw_1.settransobject(sqlca)
dw_1.retrieve()
使用SetSQLSelect有一定的要求和限制,更改后的SELECT語句在結構上必須與原先的語句匹配,在執行SetSQLSelect函數之前必須用SetTrans或SetTransObject函數設置DataWindow控件的內部事務對象。另外, DataWindow對象的數據源必須是一個不帶參數的SELECT語句,如果需要使用檢索參數,可以在程序代碼中修改SQL Select語句。
原文轉自:http://www.anti-gravitydesign.com