Friday, September 24, 2010

Understanding Convert function in SQL Server 2008.

Used to convert a value Like CAST (), the CONVERT () function. Unlike CAST (), CONVERT can be used to convert a value its original type into a non-similar type. For example, you can use CONVERT to cast a number into a string and vice-versa.

The syntax of the CONVERT () function is:

CONVERT (Data Type [ ( length ) ] , Expression [ , style ])

If you are converting the value into a string (varchar, nvarchar, char, nchar) or a binary type, you should specify the number of allowed characters the data type's own parentheses. As reviewed for the CAST () function, the Expression is the value that needs to be converted.

Example:

DECLARE @Side As Decimal(20,5),
        @Perimeter As Decimal(20,5),
        @Area As Decimal(20,5);
SET     @Side = 58.137;
SET     @Perimeter = @Side * 5;
SET     @Area = @Side * @Side;
PRINT 'Square Characteristics';
PRINT '-----------------------';
PRINT 'Side      = ' + CONVERT(varchar(20), @Side, 20);
PRINT 'Perimeter = ' + CONVERT(varchar(20), @Perimeter, 20);
PRINT 'Area      = ' + CONVERT(varchar(20), @Area, 20);
GO

The result is displayed below with CONVERT () function.

No comments:

Recent Posts