Question

Is it possible to denote a bind variable in SQL Server using the same notation as Oracle i.e. :0, :1 instead of using ?.

I have searched but not found anything conclusive on this. At the moment my solution uses bind variables to introduce values to statements that I run on the database which works great in Oracle but I also need to do the same in SQL Server and PostGIS to name a few. I dont want to have to say for example:

switch(dialect)
{
    case "Oracle":
    {
        oleDataBaseConnection.AddParameter(":1", coordsys);
        break;
    }

    case "SQLServer":
    { 
        oleDataBaseConnection.AddParameter("?", coordsys);
        break;
    }
}

*AddParameter() is a function from my wrapper class that add the values to a list to be added to the command object when calling the execute function I have written.

I would like my code to be as clean as possible and not contain hardcoded stuff as shown above. I would like a solution that fits all. (yes I know this is probably wishful thinking!)

I know I could use a string replace to do this but it is just not what I am after. I dont want to use a workaround like that really. Also my project manager requested that I try to find a solution using bind variables.

Any ideas?

Was it helpful?

Solution

The short answer is no, bind variables are implemented differently in different databases. So you'll need the messy compatibility logic somewhere.

That said, I personally have solved this problem in the past using string substitution to put in the right syntax for a bind parameter. Thus you could embed :coordsys in your SQL statement, and then oleDataBaseConnection.AddParameter("coordsys", coordsys); in your code. Your prepare statement would then search the SQL, find :coordsys and replace it by whatever you need (for instance ?), and also build up the list of parameters by name for your later execute. When you go to execute, you can on the fly build up the right list of bind parameters to use.

Implementing the behind the scenes bit is a bit tricky, but I've personally found that it leads to clean SQL, with the benefits of bind parameters (like database performance, security from SQL injection attacks).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top