简体   繁体   中英

Prepared statement with wildcard not returning certain rows but query returns all rows?

I'm using JTDS as a driver to connect to SQL server.

Here's the query that's giving me problems:

SELECT EmpID,FirstName,LastName,CompanyName,DepartmentName,JobTitle,HireDate FROM Employees where UPPER(FirstName) LIKE 'KEVIN%'

It returns 2 rows on SQL Server. One that has 'KEVIN' in upper case and another that has 'Kevin' like so. I used the wildcard to make sure I get both results. In my EmployeeDAO class I'm using the following:

        ps = con.prepareStatement("SELECT EmpID,FirstName,LastName,CompanyName,"
                + "DepartmentName,JobTitle,HireDate FROM Employees WHERE UPPER(FirstName) LIKE ?");
        ps.setString(1, FirstName + "%");
        rs = ps.executeQuery();

And then of course I put KEVIN on my main. It only returns ONE row, which is the 'Kevin' row.

How do I fix this so it returns all rows?

Default collation of the SQL Server installation is SQL_Latin1_General_CP1_CI_AS and it is not case sensitive.

Change collation of the query:

SELECT Col1
FROM Table1
WHERE Col1 COLLATE Latin1_General_CS_AS LIKE 'KEVIN%'

Your query looks fine (although I would uppercase the parameter value before setting it, to make it more robust). The problem is just in the way how you're collecting the rows from the ResultSet . Likely you're plain overriding the previous row with the next row so that you end up with only one row (the last one) in your collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM