Sql Server ignores index on varchar column and does tablescan when queried from Java

╄→гoц情女王★ 提交于 2020-01-02 06:58:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!