Search code examples
sql-serverlinuxfreetds

@variables in FreeTDS


I am attempting a quick prototype-port of some old database code over to use the FreeTDS library. Currently, I am looking at a query similar to

SELECT x,y,z from MyTable WHERE id = @arg1

When I execute the query, I naturally get an error like Must declare the scalar variable "@arg1".

But one thing eludes me. How do I declare this variable? I have looked through the API docs and code examples over and over again and I can't seem to find how to solve this should-be-trivial task.

The code I currently use is:

if(dbcmd(proc, "SELECT x,y,z from MyTable WHERE id = @arg1") != SUCCEED) {
  return fail("Failed to dbcmd()"); 
}

if(dbsqlexec(proc) != SUCCEED) {
  return fail("Failed to dbsqlexec()");
}

while((retcode=dbresults(proc)) == SUCCEED) {
  while(dbnextrow(proc) != NO_MORE_ROWS) {
    int len = dbdatlen(proc, 1);
    char* data = (char*)dbdata(proc, 1);
    cout << string(data, len) << endl;
  }
}

Solution

  • You can try either "DECLARE @MyVariable int" or "@arg1", OleDbType.Integer" to add as dbcmd(dbproc, "HERE" ); after your dbcmd(proc,"SELECT .....");

    dbcmd(dbproc,"SELECT x,y,z from MyTable WHERE id = @arg1");
    dbcmd(dbproc, "DECLARE @arg1 int" );
    

    I do'nt think if there is any API however I am sure this is the way you could use it.