Conversion functions in SQL Server 2012

data conversion

Conversion functions  in SQL Server 2012

 

Before starting with “Conversion functions in SQL Server 2012” we’ll have a look into “Why data conversion needed?”

Does SQL Server can’t do it automatically?

Yes! SQL server can do data conversion internally which is called implicit data conversion.

Implicit Data Conversion:

While evaluating any SQL expressions SQL Server database engine implicitly converts data depends on the “Datatype Precedence”. “Binary” data type is the least precedence and “User defined data type” is the highest precedence.

For example consider the below query

SELECT 10+'10'

Here 10 is an integer and ‘10’ is a string. If we run the above statement it gives output as 20

While executing the statement SQL Server compares the data type precedence between the data types INT and VARCHAR. As INT data type is having higher precedence than VARCHAR it implicitly converts the string ‘10’ to integer 10 and hence the result would be 20.

Now we’ll see one more example as below

SELECT GETDATE()

SELECT GETDATE()+10

Here GETDATE() returns DATETIME data type and 10 is an integer. Since DATETIME is higher precedence than INTEGER it adds 10 days to the current date and returns the result as below.

SQL Server implicitly converts all lower data type values to the higher data type values in an expression. Sometimes implicit conversions may lead to performance overhead. To take the control of this conversion we have to use conversion functions explicitly.

Explicit Conversion:

Below are the conversion functions available in SQL Server 2012.

  • CAST

  • CONVERT

  • PARSE

  • TRY_CAST

  • TRY_CONVERT

  • TRY_PARSE

CAST AND CONVERT: As we know that these are the functions and can be used for converting data across data types.  Functionality is similar for these two functions. Major difference between CAST and CONVERT is; CONVERT supports an extra feature called “style”. We can also mention the style of the converted data. It helps us when dealing with DATETIME datatype values.

As a traditional way of converting, we clearly know how to use these functions.

SELECT CAST('10' AS INT)+10 AS 'Total'

SELECT CONVERT(INT,10)+10 AS 'Total'

Now we’ll see how these are differentiating for “DATETIME” data values.

SELECT 'OP Completed on: '+CAST(SYSDATETIME() AS VARCHAR(30)) AS 'Msg'

SELECT 'OP Completed on: '+CONVERT(VARCHAR(30),SYSDATETIME(),106) AS 'Msg'

Here “SYSDATETIME()” is a system function to get the current date with time.  “106” is the format style in which the data must be converted.

CONVERT function will give more flexibility in handling the date related data types.

Please check here to know more about these functions.

PARSE:

It is also a string conversion function introduced in SQL Server 2012. It converts string to other datatypes. With this conversion function we can indicate the culture in which data can be converted. The culture can be any culture supported by .Net framework. Also PARSE function tries it’s best in converting strings to the intended datatypes.

It is a non SQL Server native function and depends on dotnet CLR hence there would be some performance overhead. Try to use CAST and CONVERT functions wherever possible.

Let’s have a look at few examples.

-- Convert string to Int

SELECT PARSE('100' AS INT) AS 'Integer';

-- Convert string to Decimal

SELECT PARSE('100.334' AS DECIMAL(10,3)) AS 'Decimal';

-- Convert string to DateTime using US format

SELECT PARSE('03/07/2013' AS DATETIME USING 'en-US') AS 'DateTime';

-- Convert string to DateTime using INDIA format

SELECT PARSE('03/07/2013' AS DATETIME USING 'en-IN') AS 'DateTime';

PARSE function can be more efficient in handling DATETIME data values. It performs it’s best in converting data.

CONVERT/CAST function requires the input to be specified properly, convert fails if the input is not in an acceptable format whereas PARSE can perform well in this situations. Below are the examples.

-- Let’s try to convert String to datetime using CONVERT

SELECT CONVERT(DATETIME,'WEDNESDAY Jul 03 2013')

GO

-- Let’s try to convert String to datetime using CAST

SELECT CAST('WEDNESDAY Jul 03 2013' AS DATETIME)

The CONVERT and CAST fail’s in converting string “WEDNESDAY Jul 03 2013” to datetime.

Now we’ll check the same conversion operation with PARSE

-- Lets try to convert String to datetime using PARSE

SELECT PARSE('WEDNESDAY Jul 03 2013' AS DATETIME) AS 'Str2Date'

Please have a look at here for more details.

TRY_CAST, TRY_CONVERT, TRY_PARSE:

The difference between the functions without the TRY and their counterparts with the TRY is that those without the TRY fails if the value isn’t convertible, whereas those with the TRY return a NULL in such a case.

Let’s have a look at below example to know differences between with and without TRY.

-- When we try to convert a string to INT using CAST

SELECT CAST('T100' AS INT) AS 'With CAST';

GO
-- When we try to convert a string to INT using CONVERT

SELECT CONVERT(INT,'T100') AS 'With CONVERT';

GO
-- When we try to convert a string to INT using PARSE

SELECT PARSE('T100' AS INT) AS 'With PARSE';
GO

Now we’ll try some examples with “TRY_”

-- When we try to convert a string to INT using CAST

SELECT TRY_CAST('T100' AS INT) AS 'With CAST';
GO

-- When we try to convert a string to INT using CONVERT

SELECT TRY_CONVERT(INT,'T100') AS 'With CONVERT';
GO

-- When we try to convert a string to INT using PARSE

SELECT TRY_PARSE('T100' AS INT) AS 'With PARSE';
GO

Please check the below links to know more about these functions.

TRY_CAST

TRY_CONVERT

TRY_PARSE

Posted in SQL Development | Tagged , , , , , , , , , | Leave a comment

What is the Difference between NUMERIC / DECIMAL and FLOAT / REAL in SQL Server 2012?

udayarumilli_decimals

What is the Difference between NUMERIC / DECIMAL and FLOAT / REAL

Q. What is the Difference between NUMERIC / DECIMAL and FLOAT / REAL in SQL Server 2012?

Ans:

Before dig into these data types we must have a look into precision and scale.

Precision: The maximum total number of decimal digits that can be stored both to the left and to the right of the decimal points.

Scale: The maximum number of decimal digits that can be stored to the right of the decimal point

Example:

Take an example number: 1433890.2554

Here the precision is: 11 (1433890)

Scale is: 4 (2554)

To store this number into a variable it must be declared with the proper precision and scale.

USE udayarumilli;

GO

DECLARE @Test DECIMAL(11,4) = 1433890.2554;

SELECT @Test

Output is:

—————————————
1433890.2554

(1 row(s) affected)

From the above example if we change the precision value to 10 and try to assign the same number the execution will be failed with “Arithmetic Overflow error”.

USE udayarumilli;
GO
DECLARE @Test DECIMAL(10,4) = 1433890.2554;
SELECT @Test

Output would be:

Msg 8115, Level 16, State 8, Line 1
Arithmetic overflow error converting numeric to data type numeric.

(1 row(s) affected)

As we have changed the precision value to 10 it turns into arithmetic overflow error.

Now we’ll have a look into these data types.

NUMERIC / DECIMAL: These data types are the similar in functionality and used to represent the fixed precision and scale values.  These are most apt for the situations where we need to represent accurate values that include “Price”, “Balance”, and “Credit” etc. Please have a look here to know more about these data types.

 REAL / FLOAT: These data types can be used when accuracy is not a deal. To represent the very large numbers or very small numbers that includes scientific purposes and average counts, approx. values etc. Please have a look here to know more about these data types.

We’ll demonstrate an example, and we’ll see how these data types are varying in handling the same number.

Declare a variable of type FLOAT and try to convert it into NUMERIC.

DECLARE @Var_F FLOAT = 1234567.02265;

SELECT  @Var_F AS 'Float_Value',

        CAST(@Var_F AS NUMERIC(20,10)) AS 'Numeric_Converted';

 

Can you guess the output of converted value?

Float_Value            Numeric_Converted

———————- —————————————

1234567.02265          1234567.0226499999

(1 row(s) affected)

You can clearly observe the difference between numbers.  This is the reason we should not use the columns of type Float while comparing with the other values in a table.

Means we should be very careful using these columns and conversions in WHERE clause.

 

 

Posted in SQL Development | Tagged , , , , , , , | 3 Comments

Preparing for MCSA Exam 70-461 – MS SQL Server 2012 exam

MCSA Certification Prep | Exam 461: Querying Microsoft SQL Server 2012

SQL Server Certification preparation MCSA Exam 461

exam70641

Preparing for MCSA Exam 70-461 – MS SQL Server 2012 exam

https://www.youtube.com/watch?v=cZVtrjDOEeo

  Review: Just go through this video we’ll get a over all view on preparing 70-461 exam.

Posted in Miscellaneous | Tagged , , , , , , , , | Leave a comment