in reply to Invalid character value for cast specification

I encountered this error today using DBI to update a SQL Server 2000 database using DBD::ODBC.

The problem code is as follows:

my $sql = q{select * from accountaction where action_date > ?}; my $sth = $dbh->prepare($sql); $sth->execute('01-01-2006'); $sth->finish;
The same code, but without the bound parameter worked correctly:
my $sql = q{select * from accountaction where action_date > '01-01 +-2006'}; my $sth = $dbh->prepare($sql); $sth->execute(); $sth->finish;
The issue was that DBD::ODBC did not like the MM-DD-YYYY date format.
Changing it to the following fixed the error for me:
my $sql = q{select * from accountaction where action_date > ?}; my $sth = $dbh->prepare($sql); $sth->execute('2006-01-01'); $sth->finish;
This likely occurs because SQL Server can have different date formats, e.g. DD-MM-YYYY for some locales. So to be safe it only allow the YYYY-MM-DD format.

This response is being added to a somewhat old node because it is the only relevant one I found using Super Search, and I would like to save future searchers some trouble.

Replies are listed 'Best First'.
Re^2: Invalid character value for cast specification
by larrymcp (Novice) on Mar 29, 2013 at 02:42 UTC

    Huge thanks- you did in fact "save future searchers some trouble", big time!

    I was getting this error too, and I didn't realize it was because I hadn't included the hyphens in the date. I'm so used to doing '20130325' in SQL Server, and it does accept that form in other contexts.

    But for parameterized queries, apparently one needs the hyphens like "2013-03-25', because once I read your comment and put the hyphens in, problem solved.

    (Yes I love replying to a post 7 years after it was written, just to say thanks to a guy who will probably never read this)