The DBI spec requires a driver to support :name as a parameter even though in the ODBC SQL and ODBC world ? is more usual. DBD::ODBC is seeing the :GetRoot as a parameter marker. You need to tell DBD::ODBC to ignore parameter markers starting with a : using odbc_ignore_named_placeholders.
SQL Server static method call in query causes error in Perl DBI
-
17-07-2023 - |
Question
I am trying to query a table in a SQL Server 2008 database that has a hierarchyid
for one of its columns. So in a particular query that I run from Perl using DBI, I need to use hierarchyid::GetRoot()
but this call causes a problem. A minimal (non-)working example is
SELECT OrgNode FROM lang_hier WHERE OrgNode = hierarchyid::GetRoot();
This query works in MS SQL Server Management Studio, but not from Perl, where it produces this error:
DBD::ODBC::st execute failed: [Microsoft][ODBC SQL Server Driver]COUNT field inc
orrect or syntax error (SQL-07002) at mwe.pl line 11.
In Perl, however, I'm running it as a prepared statement (which isn't necessary for the minimal example, but I do need it) and I suspect that the colons are causing problems. I can't seem to find a way to escape the colons to make it work. Is there any other way to get it working?
Edit: using a normal query (not a prepared statement) actually produces the same error.
use strict;
use warnings;
use DBI;
my ($_dbserver, $_dbname, $_dbuser, $_dbpassword) = (...);
my $query = 'SELECT OrgNode FROM lang_hier WHERE OrgNode = hierarchyid::GetRoot();';
my $dbh = DBI->connect("dbi:ODBC:Driver={SQL Server};Server=$_dbserver;UID=$_dbuser;PWD=$_dbpassword")
or die "Can't connect to server: $DBI::errstr";
my $sth = $dbh->prepare($query);
$sth->execute;
$dbh->disconnect();
Solution