Pages

Friday, January 18, 2008

Casting a Value

In most cases, a value the that you submit to your database is primarily considered a string. This is convenient if that's what you are expecting. If the value that you provide must be treated as something other than a string, for example, if you provide a number, before using such a value, you should first convert it to the appropriate type, that is, from a string to the expected type.

To assist with conversion, you can use either the CAST() or the CONVERT() function. The syntax of the CAST() function is:

CAST(Expression AS DataType)
The Expression is the value that needs to be cast. The DataType factor is the type of value you want to convert the Expression to.

In the following example, two variables are declared and initialzed as strings. Because they must be involved in a multiplication, each is converted to a Decimal type:

DECLARE @StrSalary Varchar(10),
@StrHours Varchar(6),
@WeeklySalary Decimal(6,2)
SET @StrSalary = '22.18';
SET @StrHours = '38.50';

SET @WeeklySalary = CAST(@StrSalary As Decimal(6,2)) *
CAST(@StrHours As Decimal(6,2));
SELECT @WeeklySalary;
GO

No comments: