Search code examples
sqlcursor

SQL Cursor Fetch Data without knowing Table Description


I am writing a Pro* C function which would accept the table name and return the values stored in it.

select * from <table_name>

Now what we know from the basic programming of cursor is:

DECLARE 
emp_rec emp_tbl%rowtype;
CURSOR emp_cur IS 
SELECT *
FROM 
WHERE salary > 10; 
 BEGIN 
    OPEN emp_cur; 
    FETCH emp_cur INTO emp_rec; 
     dbms_output.put_line (emp_rec.first_name || '  ' || emp_rec.last_name); 
   CLOSE emp_cur; 
END;

here in the above code we need the table description so that we can use statements like

emp_rec.first_name
emp_rec.last_name

Suppose if we don't know about the description of table then how can we get the values from the cursor.

Is it possible.?


Solution

  • To achieve the above desired, I have developed an API for Pro*C, which has several functions and inbuilt classes to make DB interaction using Pro*C really easy. See CODBC.

    Sample Code:

     int main()
     {
          SQLHelper DB("username","password");
          vector< vector<string> > rowData;
          try
          {
               DB.openDB(); //connect to oracle database
               if(DB.checkDBStatus())  //if connected to database or not
               {
                    cout<<"connected"<<endl;
               }
               rowData=DB.selectDB("select to_char(sysdate) from dual"); //fetch all rows in rowData
               if(rowData.size()>0) //to check if rows are fetched or not
               {
                    for(int i=0;i<rowData.size();i++) //access each row
                    {
                         for(int j=0;j<rowData.at(i).size();j++) //access each column
                         {
                              cout<<rowData.at(i).at(j);
                         }
                         cout<<endl;
                    }
               }
               else
               {
                    cout<<"No rows fetched"<<endl;
               }
          }
          catch(SQLHelperException sqlExp) //catch any exception during SQL execution
          {
               cout<<sqlExp.getExceptionString()<<endl;
          }
          return 0;
     }
    

    This is how we can retrieve any table without knowing it description.