Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

10 reasons to explicitly convert Version 1.

0
SQL Server data types March 13, 2008

By Susan Sales Harkins


SQL Server converts data types in two ways -- the way it wants to and the way you tell it to. Most implicit conversions
work the way you expect. It’s the surprise conversion that causes trouble. Unless you know exactly how SQL Server
converts a data type, I recommend that you explicitly convert data types. Most of the time you’ll use CAST or
CONVERT to control the conversion outcome.

CAST to eliminate format


1
Use CAST, as follows, to explicitly convert an expression when you don’t want or need to format the results:
CAST(expression AS datatype)
Strictly speaking, you probably won’t convert just to eliminate a format, but it’s nice to know you can eliminate
formatting and convert in one step. There’s one catch: SQL Server must support datatype; this function doesn’t
support user-defined data types.
Visit http://msdn2.microsoft.com/en-us/library/ms187752.aspx to learn more about SQL Server data types.

CONVERT to format
2
CONVERT lets you convert and format in one step as follows, where style specifies the format:
CONVERT (datatype, expression, style)
Like CAST, datatype must be system-supported, as it won’t work with user-defined data types. Visit
http://msdn2.microsoft.com/en-us/library/ms187928.aspx to view a list of style values.

CAST for decimals


3
If you let SQL Server choose, there’s no
guarantee that it will return the data type you expect
when evaluating data. For instance, the statement in
Figure A returns an integer instead of the exact
number because SickLeaveHours is an int column.
Compare the above results to those in Figure B. By
converting SickLeaveHours values to a numeric data
type before evaluating them, the expression returns
the decimal component. Converting the expression’s
results won’t work because it’s too late.

Figure A

Figure B

Page 1
Copyright ©2008 CNET Networks, Inc. All rights reserved.
For more downloads and a free TechRepublic membership, please visit http://techrepublic.com.com/2001-6240-0.html
10 reasons to explicitly convert SQL Server data types

CAST to truncate
4
When trying to convert decimal values into
integers, you might start with ROUND. However, that
function doesn’t always get the job done. For
instance, suppose your shipping volume is so great
that your distribution company charges by the
smaller whole unit—forgiving the overage into the
next pound. In other words, if the item weighs 2.5
pounds, the company charges for only 2.
In this case, you’d need to know the shipping weight
and not necessarily the item’s true weight. As you
can see in Figure C, this is one of those times when Figure C
ROUND doesn’t work. It rounds down in some
cases, which works. In other cases, it rounds up,
and you’d pay more money than necessary.
In Figure D, CAST solves the problem. In this
case, converting the weight value to an integer
truncates the decimal portion.

CAST and CONVERT to


5 concatenate
SQL Server won’t concatenate values of different
data types. Furthermore, concatenation is strictly a
string function. That means you must convert all
values to strings before SQL Server will
concatenate them. Figure E shows the error
returned when an expression attempts to Figure D
concatenate a numeric value (Weight) to a string.
For concatenation to work, use CAST to convert
the numeric value to a string, as shown in Figure
F. Once the numeric weight value is a string, SQL
Server can concatenate properly.
CONVERT works almost interchangeably with
CAST in regards to concatenation. Figure G
shows the same concatenation expression using Figure E
CONVERT instead of CAST.

Figure F

Page 2
Copyright ©2008 CNET Networks, Inc. All rights reserved.
For more downloads and a free TechRepublic membership, please visit http://techrepublic.com.com/2001-6240-0.html
10 reasons to explicitly convert SQL Server data types

CAST and CONVERT


6
variants—always
As a general rule, you should avoid using SQL
Server's sql_variant data type. Besides being a
memory hog, sql_variant is limited:
• Variants can’t be part of a primary or foreign
key.
• Variants can’t be part of a computed column.
• Variants won’t work with LIKE in a WHERE
clause.
• OLE DB and ODBC providers automatically
convert variants to nvarchar(4000) -- ouch! Figure G

To avoid problems, always explicitly convert


sql_variant data types as you use them. Use any
method you please, just don’t try to work with an
unconverted sql_variant data type.

CONVERT for date


7
components
Functions won't always return a datetime value just
because the expression evaluates a datetime data
type. SQL Server is generally smart enough to get
the implicit conversion correct. As you can see in
Figure H, with or without converting, the resulting
values are correct -- depending upon your needs.
This conversion decision is similar to #4 and #5.
The problem is, you might not expect to have this
problem with a datetime data type.

Figure H
8 CONVERT datetime to a string
It’s impossible to get rid of the date or the time component in
a datetime data type, but you can work with the date and
time values separately. One way to get the date is to convert
the datetime value to an unformatted string, as shown in
Figure I. The good news is that SQL Server correctly
interprets the unformatted string, regardless of datetime or
language settings, when you convert the string back to
datetime.

Figure I

Page 3
Copyright ©2008 CNET Networks, Inc. All rights reserved.
For more downloads and a free TechRepublic membership, please visit http://techrepublic.com.com/2001-6240-0.html
10 reasons to explicitly convert SQL Server data types

CAST for quicker search


9
If a numeric search or sort is slow, try converting to a character data type to speed things up. This trick won’t
always be appropriate, but when it works, it works great. Simply convert the searched numeric column in the WHERE
clause as follows:
WHERE CAST(column AS char(n)) condition
For example, the conversion in the following WHERE clause improves server statistics:
USE AdventureWorks
SELECT * FROM HumanResources.EmployeeSick
WHERE CAST(SickLeaveHours AS char(3)) <> 0
You’ll need a lot of records to notice the improvement, and it won’t always work. To view statistics for a specific query,
choose Query Options from the Query menu (in Management Studio). Expand the Advanced node, check SET
STATISTICS TIME and SET STATISTICS IO, and click OK. Run the query and compare statistics listed in the
Messages tab.

CAST for quick date fix


10
When date values aren’t datetime data types, you
can still depend on date arithmetic if you convert the strings
first, as shown in Figure J.
Use CONVERT when the string format is ambiguous, such
as mm/dd/yyyy and dd/mm/yyyy.

Figure J

A word of warning
It’s important to note something that seems obvious but that we often forget. Use converted results for only the
purpose intended. It’s just too easy to forget about the conversion and in doing so, to generate subsequent errors that
are hard to debug.

Susan Sales Harkins is an independent consultant and the author of several articles and books on database
technologies. Her most recent book is Mastering Microsoft SQL Server 2005 Express, with Mike Gunderloy, published
by Sybex. Other collaborations with Gunderloy are Automating Microsoft Access 2003 with VBA, Upgrader’s Guide to
Microsoft Office System 2003, ICDL Exam Cram 2, and Absolute Beginner's Guide to Microsoft Access 2003, all
published by Que. Currently, Susan volunteers as the Publications Director for Database Advisors. You can reach her
at ssharkins@gmail.com.

Page 4
Copyright ©2008 CNET Networks, Inc. All rights reserved.
For more downloads and a free TechRepublic membership, please visit http://techrepublic.com.com/2001-6240-0.html
10 reasons to explicitly convert SQL Server data types

Additional resources

TechRepublic's Downloads RSS Feed


Sign up for the Downloads at TechRepublic newsletter
Check out all of TechRepublic's free newsletters
Sign up for our SQL Server newsletter
How do I... Reject alpha characters in a SQL Server character column?
How do I... Query foreign data using SQL Server's linked servers?
How do I... Enforce domain integrity for SQL Server data using CHECK constraints?

Version history
Version: 1.0
Published: March 13, 2008

Tell us what you think

TechRepublic downloads are designed to help you get your job done as painlessly and effectively as possible.
Because we're continually looking for ways to improve the usefulness of these tools, we need your feedback.
Please take a minute to drop us a line and tell us how well this download worked for you and offer your
suggestions for improvement.

Thanks!

—The TechRepublic Content Team

Page 5
Copyright ©2008 CNET Networks, Inc. All rights reserved.
For more downloads and a free TechRepublic membership, please visit http://techrepublic.com.com/2001-6240-0.html

You might also like