Ian Jose's WebLog

This weblog is intended to help T-SQL developers get the best performing query plans from SQL Server. Some of the posts describe simple mistakes that can be easily avoided. Other posts describe complex solutions to limitations in SQL Server. Lastly, some posts describe recent improvements in SQL Server, and the means to employ them best.

Avoid Unnecessary Data Type Conversions

SQL Server adds implicit data type conversions when types don’t match.  This can have unintended results both on query results, but also on the query plan.  It is important to use literal constants that match in type column they are being compared with wherever possible.  A common mistake in writing T-SQL is to always use string literals for constants even when those constants are numbers, for example.

SELECT * FROM Sales

WHERE Quantity = ‘100’

In this example, ‘100’ is a character string while the column Quantity is an integer.  The implicit conversion used follows strict precedence rules.  Here the conversion will be on Quantity to character string, and not on the ‘100’ to an integer. 

Published Thursday, November 10, 2005 1:58 PM by ianjo

Comments

 

Stored Procedure Guidelines: Avoid magic numbers said:

October 4, 2006 4:10 AM
 

diegov said:

Ian José, I think it is even worse when you do the oposite:

SELECT Quantity FROM Sales WHERE Status = 1

Status being a string column. Unfortunatelly SQL Server will let you do this until some day someone adds a status code in a row that cannot be converted to a number!

Add to this the fact that SqlCommand.ExecuteScalar sometimes fails to raise an error on this condition, and you have a bug that is very difficult to chase (I know because this have just happened in my company).

My wish: that I could disable implicit conversions by using some phrase in the connection string. Kind of "Option Strict = True;" :)

November 17, 2006 11:21 AM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker