问题
QUESTION: I have a SQL Server table with one varchar column and millions of rows, it is indexed. Running a query from within SQL Server query tool is quick as it uses the index. When I run a query from Java JDBC PreparedStatement it takes many minutes and investigation shows SQL Server does a tablescan. How do I fix this problem?
回答1:
ANSWER: The problem results from Java passing a unicode string for the query parameter to SQLServer. SQLServer will not use this on a varchar index.
If you want the column to stay varchar (or cannot change it) and have access to the Java code, set the sendStringParametersAsUnicode connection string property to "false" (it defaults to "true"). Search "MSDN International Features of the JDBC Driver" for more details but also applies with CHAR, VARCHAR or LONGVARCHAR columns.
If you don't have access to the Java code but can change the database, changing the varchar column in the database to nvarchar will fix the problem at the cost of doubling data storage requirements.
EXAMPLE
jdbc:sqlserver://localhost:1433;databaseName=mydb;sendStringParametersAsUnicode=false
来源:https://stackoverflow.com/questions/28821915/sql-server-ignores-index-on-varchar-column-and-does-tablescan-when-queried-from