Marquis Blount
Marquis Blount

Reputation: 8095

Using datediff in sql jdbc query

I'm attempting to create a JDBC query with the following statement

String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName +
            "where datediff(d,DATECOLUMN2,getdate()) <= 1";
st = conn1.createStatement();
rs = st.executeQuery(query);  //receiving error here

I am receiving the following error message

java.sql.SQLException: "d" is not a recognized table hints option. If it is intended as a parameter to a table-valued function or to the CHANGETABLE function, ensure that your database compatibility mode is set to 90.

I'm sure the query isn't recognizing the datediff function for some reason I am not sure why since i was previously using HQL in the same application and retrieving the values.

In an attempt to use an alternative function I used

{fn TIMESTAMPADD( SQL_TSI_DAY, 1, CURRENT_TIMESTAMP)}

but it also failed I later on found that this is only used for Derby Database's

Can someone assist me in using the proper sql function to compare a date with the current date using JDBC

Upvotes: 0

Views: 2708

Answers (4)

Andriy M
Andriy M

Reputation: 77667

The posted snippet doesn't have a closing double quote between tableName and +, but I figure that is just a typo. However, in your real code, where precisely is the double quote? Is it directly after tablename, like this

String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName" +

or after the space that follows tablename, like this

String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName "+

It is very likely the former, because in that case the resulting query would look exactly the way as to cause the error you are getting. Take a look at this:

SELECT COLUMN1,DATECOLUMN2 FROM tableNamewhere datediff(d,DATECOLUMN2,getdate()) <= 1

You can see that where merges with the table name and datediff becomes an alias. What follows is interpreted as table hints. (You can specify table hints without WITH in older versions of SQL Server/older compatibility levels.) Consequently, SQL Server stumbles over d, as that is indeed an incorrect table hint.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425013

The comma after the "d" should be a dot:

where datediff(d.DATECOLUMN2,getdate())
--------------- ^ dot here

Upvotes: 0

user1965397
user1965397

Reputation: 1

You have a comma before from. Based on the error messages you are running this against SQL server.

String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName " 
              +" where datediff(d,DATECOLUMN2,getdate()) <= 1";

Upvotes: 0

John Woo
John Woo

Reputation: 263723

String query = "SELECT COLUMN1,DATECOLUMN2 FROM tableName "+
               "where datediff(day,DATECOLUMN2,getdate()) <= 1";

Upvotes: 3

Related Questions