動態SQL語句的兩種執行方式
阿新 • • 發佈:2022-02-15
1.如果SQL語句已經被構造在host-variable字串變數中,則
(1)立即執行語句:執行時編譯並執行(構造的字串SQL內部沒有“變數”引數)
exec sql execute immediate :host-variable;
(2)Prepare-Execute-Using語句:Prepare語句先編譯,編譯後的SQL語句允許動態引數(即允許高階語言傳遞引數到SQL語句中),execute語句執行,用using語句將動態引數值傳遞給編譯好的SQL語句(構造的字串SQL內部有“變數”引數)
exec sql prepare sql_temp from :host-variable; // 預編譯
... ...
exec sql execute sql_temp using :cond-variable; //cond-variable 動態引數
2.Prepare-Execute-Using舉例
1 //Prepare-Execute-Using 2 #include<stdio.h> 3 #include"prompt.h" 4 exec sql include sqlca; 5 exec sql begin declare section; 6 char cust_id[5]; 7 char sqltext[256]; 8View Codechar user_name[20]; 9 char user_pwd[10]; 10 exec sql end declare section; 11 char cid_prompt[] = "Name customer cid to be deleted: "; 12 13 int main() 14 { 15 strcpy(sqltext,"delete from customers where cid = :dcid"); 16 ... ... 17 while(prompt(cid_prompt, 1, cust_id, 4)>=0) 18{ 19 exec sql whenever not found goto no_such_cid; 20 exec sql prepare delcust from :sqltext; //為編譯提供了基礎 21 exec sql execute delcust using :cust_id; //cust_id是輸入的字串變數 22 exec sql commit work; 23 24 no_such_cid:printf("No cust %s in table\n",cust_id); 25 continue; 26 } 27 ... 28 }