Data type conversion and CAST function page 2 |
||||||||||||
Let us consider another example. Example 5.9.2 Define the average launching year from the Ships table. The query gives 1926. In principle, it is correct, because a year is integer number. However arithmetic mean will be about 1926,9091. It should be noted that aggregate functions (except COUNT which always returns integer value) inherits the type of data to be processed. Because the launched field is integer-valued, we have gotten the average value without fractional part (not rounded off).What must we do if the result ought to be obtained with two digits after decimal point? As mentioned above, applying the CAST statement to the average value gives no result. Indeed, The result - 1926.90909- is not exactly correct. This is because of implicit conversion that was accomplished when calculating the average value. Another step:
It is the correct result - 1926.91. However this solution looks too cumbersome. Let implicit conversion to work for us: Thus, we use implicit conversion of the argument from integer to exact numeric type by multiplying it by real unity. After that, explicit conversion is applied to the result of the aggregate function. The same conversions can be made with aid of the CONVERT function: The CONVERT function has the following syntax:
The main distinction of the CONVERT function from the CAST statement is that the first allows formatting data (for example, temporal data of datetime type) when converting them to character data and specifying the format when converting character data to datetime. The values of integer optional argument style correspond to different formats. Let us consider the following example: Here, the string representation of a date is converted to datetime following the reverse conversion to demonstrate the result of formatting. Since the style argument is omitted, default value is used (0 or 100). As a result, we obtain Jul 22 2003 12:00AM Below are some values of the style argument and corresponding results from the above example. Note, the style values greater than 100 give four-place year.
All possible values of the style argument are given in BOL. Suggested exercises: 32, 35, 53, 54, 58, 69, 78, 81, 91, 115, 119 |