Method 3 example

The following example uses prepare and fetch, and prompts the user for an order by clause in a select statement:

exec sql begin declare section;
 CS_CHAR     sqlstring[200]; 
 CS_FLOAT    bookprice,condprice; 
 CS_CHAR     booktitle[200]; 
 exec sql end declare section; 
  
 char    orderby[150]; 
  
 exec sql whenever sqlerror call err_p(); 
 exec sql whenever sqlwarning call warn_p(); 
  
 strcpy(sqlstring, 
 "select title,price from titles\ 
 where price>? order by "); 
  
 printf("Enter the order by clause:"); 
 scanf("%s", orderby); 
 strcat(sqlstring, orderby); 
  
 exec sql prepare select_state from :sqlstring; 
 exec sql declare select_cur cursor for select_state; 
  
 condprice = 10;  /* the user can be prompted 
                   ** for this value */ 
  
 exec sql open select_cur using :condprice; 
 exec sql whenever not found goto end; 
  
 for (;;) 
 { 
     exec sql fetch select_cur 
       into :booktitle,:bookprice; 
     printf("%20s  %bookprice=%6.2f\n",
         booktitle, bookprice); 
 } 
  
 end: 
  
 exec sql close select_cur; 
 exec sql commit work;