A Review of Built-Functions
A Review of Built-Functions
A Review of Built-Functions
<a
A Review of Built-Functions
Built-In Functions Fundamentals
Introduction
While your primary job as a database developer consists of creating lists, probably your second most important job is to assist your users with the various assignments they must perform on your application. One way you can assist is to use functions that perform otherwise complex tasks. We introduced and described functions in the previous lesson. To assist your development with the different tasks of a database, Transact-SQL ships with various already created and tested functions. You just need to be aware of these functions, their syntax, and the results they produce. To help you identify the functions you can use, they are categorized by their types and probably their usefulness. Because of their complexities, some values can be easily recognized or fixed. For example, a date such as January 6, 1995 is constant and can never change. This type of value is referred to as deterministic because it is always the same. In the same way, a time value such as 5PM is constant and cannot change. There are other values that cannot be known in advance because they change based on some circumstances. For example, the starting date of the school year changes from one year to another but it always occurs. This means that, you know it will happen but you don't know the exact date. Such a value is referred to as non-deterministic. To support determinism and non-determinism, Transact-SQL provides two broad categories of functions. A function that always returns the same or known value is referred to as deterministic. A function whose returned value may depend on a condition is referred to as non-deterministic.
Casting a Value
In most cases, a value the user submits to your database is primarily considered a string. This is convenient if that's what you are expecting. If the value the user provides must be treated as something other than a string, for example, if the user provides 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. The DataType can be one of those we reviewed in Lesson 4. 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 Here is an example of executing the above statement:
Converting a Value
Like CAST(), the CONVERT() function is used to convert a value. 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(DataType [ ( length ) ] , Expression [ , style ]) The first argument must be a known data type, such as those we reviewed in Lesson 4. 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. Here is an example: -- Square Calculation DECLARE @Side As Decimal(10,3), @Perimeter As Decimal(10,3), @Area As Decimal(10,3); SET @Side = 48.126; SET @Perimeter = @Side * 4; SET @Area = @Side * @Side; PRINT 'Square Characteristics'; PRINT '-----------------------'; PRINT 'Side = ' + CONVERT(varchar(10), @Side, 10); PRINT 'Perimeter = ' + CONVERT(varchar(10), @Perimeter, 10); PRINT 'Area = ' + CONVERT(varchar(10), @Area, 10);
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/functions.htm (2 of 34)11/26/2008 5:20:07 PM
String-Based Functions
Introduction
The string is the most basic, the primary value that is presented to a database. This is because, any value, before being treated particularly, is firstly considered a string. In an application, there are various ways you use or get a string. You can get it or provide it to a function as a constant string, that is, a string whose value you know certainly and that you pass to a function. You can also get a string that a user provides. Other functions also can produce or return a string. To assist you with managing strings or performing operations on them, Transact-SQL provides various functions. The functions can divide in categories that include character-based, conversions, addition, sub-strings, etc.
DECLARE @ES varchar(100) SET @ES = 'El Salvador' SELECT @ES AS ES SELECT ASCII(@ES) AS [In ASCII Format] This would produce:
3. Press F5 to execute the statement 4. Save the code as Exercise 5. Press Ctrl + A to select the code and press Delete to remove the code 6. To test the function, type the following: SELECT Exercise1.dbo.GetUsername('Francine', 'Moukoko'); GO
8. In the Object Explorer, expand the Databases node if necessary, and expand Exercise1 9. Expand Programmability 10. Expand Functions 11. Expand Scalar-Valued Functions 12. Right-click dbo.GetUserName and click Delete 13. In the Delete Object dialog box, click OK
-- ============================================= -- Function: GetUsername -- ============================================= CREATE FUNCTION GetUsername (@FirstName varchar(40), @LastName varchar(40)) RETURNS varchar(50) AS BEGIN DECLARE @Username AS varchar(50); SELECT @Username = LOWER(LEFT(@FirstName, 1)) + LEFT(LOWER(@LastName), 4) RETURN @Username; END GO
3. Press F5 to execute the statement 4. Delete the code in the query window 5. To test the function, type the following: SELECT Exercise1.dbo.GetUsername('Francine', 'Moukoko'); GO
7. Change the call with a last name shorter than 5 characters such as "Um" and execute the statement. Here is an example:
3. Press F5 to execute the statement 4. Delete the previous code from the query window 5. To test the function, type the following: SELECT Exercise1.dbo.Last4DigitsOfSSN('836483846'); GO
-- ============================================= -- Function: Last4DigitsOfSSN -- ============================================= CREATE FUNCTION Last4DigitsOfSSN(@SSN varchar(12)) RETURNS char(4) AS BEGIN DECLARE @StringWithoutSymbol As varchar(12); -- First remove empty spaces SET @StringWithoutSymbol = REPLACE(@SSN, ' ', ''); -- Now remove the dashes "-" if they exist SET @StringWithoutSymbol = REPLACE(@StringWithoutSymbol, '-', ''); RETURN RIGHT(@StringWithoutSymbol, 4); END GO
4. Execute the statement 5. Delete the code in the query window 6. To test the function, type the following SELECT Exercise1.dbo.Last4DigitsOfSSN('244-04-8502'); GO
Arithmetic Functions
The Sign of a Number
In arithmetic, a number is considered as being negative (less than 0), null (equal to 0), or positive (higher than 0). When a number is negative, it must have a - symbol to its left. If it is positive, it may display a + symbol to its left or it can omit it. A number without the - or + symbol to its left is considered positive, also referred to as unsigned. The symbol that determines whether a number is positive or negative is referred to as its sign. The sign is easily verifiable if you know the number already. In some cases, when a number is submitted to your application, before taking any action, you may need to get this piece of information. To find out if a value is positive, null, or negative, Transact-SQL provides the SIGN() function. Its syntax is: SIGN(Expression) This function takes as argument a number or an expression that can be evaluated to a number. The interpreter would then examine the number:
q
If the Expression is positive, the function returns 1. Here is an example: DECLARE @Number As int; SET @Number = 24.75; SELECT SIGN(@Number) AS [Sign of 1058]; GO
If the Expression is null, the function returns 0 DECLARE @Number As int; SET @Number = 0; SELECT SIGN(@Number) AS [Sign of Number]; GO
If the Expression is negative, the function returns -1 DECLARE @Number As int; SET @Number = -57.05; SELECT SIGN(@Number) AS [Sign of -57.05]; GO
Based on this, you can use the SIGN() function to find out whether a value is negative, null, or positive: simply pass the value (or a variable) to SIGN() and use a logical operator to check its sign. Here is an example: -- Square Calculation DECLARE @Side As Decimal(10,3), @Perimeter As Decimal(10,3), @Area As Decimal(10,3); SET @Side = 48.126; SET @Perimeter = @Side * 4; SET @Area = @Side * @Side; IF SIGN(@Side) > 0 BEGIN PRINT 'Square Characteristics'; PRINT '-----------------------'; PRINT 'Side = ' + CONVERT(varchar(10), @Side, 10); PRINT 'Perimeter = ' + CONVERT(varchar(10), @Perimeter, 10); PRINT 'Area = ' + CONVERT(varchar(10), @Area, 10); END; ELSE PRINT 'You must provide a positive value'; GO Here is an example of executing the statement:
Notice that the interpreter acts differently in response to the result of the SIGN() function.
In the same way, consider a number such as 24.06. As this number is negative, it is between 24 and 25, with 24 being greater. In algebra, the ceiling of a number is the closest integer that is greater than or higher than the number considered. In the first case, the ceiling of 12.155 is 13 because 13 is the closest integer greater than or equal to 12.155. The ceiling of 24.06 is 24. To get the ceiling of a number, Transact-SQL provides the CEILING() function. Its syntax is: CEILING(Expression) This function takes as argument a number or an expression that can evaluate to a number. After the conversion, if the function succeeds, it returns a double-precision number that is greater than or equal to Expression. Here is an example: DECLARE @Number1 As Numeric(6, 2), @Number2 As Numeric(6, 2) SET @Number1 = 12.155; SET @Number2 = -24.06; SELECT CEILING(@Number1) AS [Ceiling of 12.155], CEILING(@Number2) AS [Ceiling of 24.06]; GO This would produce:
Here is another way of displaying the above results: DECLARE @Number1 As Numeric(6, 2), @Number2 As Numeric(6, 2) SET @Number1 = 12.155; SET @Number2 = -24.06; PRINT 'The ceiling of 12.155 is ' + CONVERT(varchar(10), CEILING(@Number1)); PRINT 'The ceiling of 24.06 is ' + CONVERT(varchar(10), CEILING(@Number2)); GO This would produce:
In this case, you can use a control statement to find out whether the Expression is positive. Here is an example: DECLARE @Number As Decimal(6, 2); SET @Number = 258.4062; IF SIGN(@Number) > 0 PRINT 'The square root of 258.4062 is ' + CONVERT(varchar(12), SQRT(@Number)); ELSE PRINT 'You must provide a positive number'; GO
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/functions.htm (24 of 34)11/26/2008 5:20:07 PM
Measure-Based Functions
Introduction
A circle is a series of distinct opposite points positioned each at an exact same distance from another point referred to as the center. The distance from the center C to one of these equidistant points is called the radius, R. The line that connects all of the points that are equidistant to the center is called the circumference of the circle. The diameter is the distance between two points of the circumference to the center. In other words, a diameter is double the radius. To manage the measurements and other related operations, the circumference is divided into 360 portions. Each of these portions is called a degree. The unit used to represent the degree is the degree, written as . Therefore, a circle contains 360 degrees, that is 360. The measurement of two points A and D of the circumference could have 15 portions of the circumference. In this case, this measurement would be represents as 15. The distance between two equidistant points A and B is a round shape geometrically defined as an arc. An angle is the ratio of the distance between two points A and B of the circumference divided by the radius R. This can be written as:
PI
The letter , also written as PI, is a number used in various mathematical calculations. Its approximate value is 3.1415926535897932. The calculator of Microsoft Windows represents it as 3.1415926535897932384626433832795. To get the value of PI, Transact-SQL provides the PI() function. Its syntax is simply: PI()
Radians
An angle is the ratio of an arc over the radius. Because an angle is a ratio and not a physical measurement, which means an angle is not a dimension, it is independent of the size of a circle. Obviously the angle represents the number of portions covered by three points. A better unit used to measure an angle is the radian or rad. If you know the value of an angle in degrees and you want to get the radians, Transact-SQL provides the RADIANS() function. Its syntax is:
RADIANS(Expression) This function takes as argument a value in degrees. If it succeeds in its calculation, it returns the radians value. A cycle is a measurement of the rotation around the circle. Since the rotation is not necessarily complete, depending on the scenario, a measure is made based on the angle that was covered during the rotation. A cycle could cover part of the circle, in which case the rotation would not have been completed. A cycle could also cover the whole 360 of the circle and continue there after. A cycle is equivalent to the radian divided by 2 * Pi.
Degrees
If you know the radians but want to get the degrees of an angle, you can use the DEGREES() function. Its syntax is: DEGREES(Expression) This function takes as argument a value in radians. If it succeeds, it returns the equivalent value in degrees.
Trigonometric Functions
The Cosine of a Value
Consider AB the length of A to B, also referred to as the hypotenuse. Also consider AC the length of A to C which is the side adjacent to point A. The cosine of the angle at point A is the ratio AC/AB. That is, the ratio of the adjacent length, AC, over the length of the hypotenuse, AB:
The returned value, the ratio, is a double-precision number between 1 and 1. To get the cosine of an angle, you can call the COS() function. Its syntax is: COS(Expression) The angle to be considered is passed as the argument to this function. The function then calculates and returns its cosine. Here is an example: DECLARE @Angle As Decimal(6, 3); SET @Angle = 270; SELECT COS(@Angle) AS [Cosine of 270]; GO This would produce:
Consider AB the length of A to B, also called the hypotenuse to point A. Also consider CB the length of C to B, which is the opposite side to point A. The sine represents the ratio of CB/AB; that is, the ratio of the opposite side, CB over the hypotenuse AB. To get the sine of an angle, you can use the SIN() function whose syntax is: SIN(Expression) The angle to be considered is passed as the argument. After its calculation, the function returns the sine of the angle between 1 and 1. Here is an example: DECLARE @Angle As Decimal(6, 3); SET @Angle = 270; SELECT SIN(@Angle) AS [Sine of 270]; GO This would produce:
In geometry, consider AC the length of A to C. Also consider BC the length of B to C. The tangent is the result of BC/AC, that is, the ratio of BC over AC. To get the tangent of an angle, you can use the TAN() function of Transact-SQL. Its syntax is: TAN(Expression) Here is an example: DECLARE @Angle As Decimal(6, 3); SET @Angle = 270; SELECT TAN(@Angle) AS [Tangent of 270]; GO This would produce:
Date/Time Addition
One of the primary operations you may want to perform on a date or a time value would consist of adding a value to it. To support this operation, Transact-SQL provides the DATEADD() function. Its syntax is: DATEADD(TypeOfValue, ValueToAdd, DateOrTimeReferenced) The third argument to this function is the value of a date or a time on which the operation will be performed. It can be a constant value in the form of 'year/month/day' for a date or 'hour:minutes AM/ PM' for a time. The second argument is the value that will be added. It should be a constant integer, such as 8, or a
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/functions.htm (30 of 34)11/26/2008 5:20:07 PM
floating point value, such as 4.06. When calling this function, you must first specify the type of value that you want to add. This type is passed as the first argument. It is used as follows:
q
If you want to add a number of years to a date, specify the TypeOfValue as Year or yy, or yyyy (remember that SQL is case-insensitive). Here is an example: DECLARE @Anniversary As DateTime; SET @Anniversary = '2002/10/02'; SELECT DATEADD(yy, 4, @Anniversary) AS Anniversary; GO
If you want to add a number of quarters of a year to a date, specify the TypeOfValue as Quarter or d, or qq. Here is an example: DECLARE @NextVacation As DateTime; SET @NextVacation = '2002/10/02'; SELECT DATEADD(Quarter, 2, @NextVacation) AS [Next Vacation]; GO
If you want to add a number of months to a date, specify the TypeOfValue as Month or m, or mm. The following example adds 5 months to its date: DECLARE @SchoolStart As DateTime; SET @SchoolStart = '2004/05/12'; SELECT DATEADD(m, 5, @SchoolStart) AS [School Start]; GO
In the same way, you can add values as follows: Type of Value Year quarter Abbreviation yy yyyy q qq As a result A number of years will be added to the date value A number of quarters of a year will be added to the date value
m mm y dy d dd wk ww hh n mi s ss ms
A number of months will be added to the date value A number of days of a year will be added to the date value A number of days will be added to the date value A number of weeks will be added to the date value A number of hours will be added to the time value A number of minutes will be added to the time value A number of seconds will be added to the time value A number of milliseconds will be added to the time value
Date/Time Subtraction
Another regular operation performed on a date or a time value consists of getting the number of units that has elapsed in the range of two dates or two time values. To support this operation, Transact-SQL provides the DATEDIFF() function. Its syntax is: DATEDIFF(TypeOfValue, StartDate, EndDate) This function takes three arguments. The second argument is the starting date or the starting time of the range to be considered. The third argument is the end or last date or time of the considered range. You use the first argument to specify the type of value you want the function to produce. This argument uses the same value as those of the DATEADD() function: Type of Value Year quarter Month dayofyear Day Week Hour minute second millisecond Abbreviation yy yyyy q qq m mm y dy d dd wk ww hh n mi s ss ms As a result The function will return the number of years that have elapsed between the start and the end dates The function will return the number of quarters of a year that have elapsed between the start and the end dates The function will return the number of months that have elapsed between the start and the end dates The function will return the number of days of a year that have elapsed between the start and the end dates The function will return the number of days that have elapsed between the start and the end dates The function will return the number of weeks that have elapsed between the start and the end dates The function will return the number of hours that have elapsed between the start and the end times or dates The function will return the number of minutes that have elapsed between the start and the end times or dates The function will return the number of seconds that have elapsed between the start and the end times or dates The function will return the number of milliseconds that have elapsed between the start and the end times or dates
Here is an example that calculates the number of years that an employees has been with the company: DECLARE @DateHired As DateTime,; @CurrentDate As DateTime;
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/functions.htm (33 of 34)11/26/2008 5:20:07 PM
SET @DateHired = '1996/10/04'; SET @CurrentDate = GETDATE(); SELECT DATEDIFF(year, @DateHired, @CurrentDate) AS [Current Experience]; GO This would produce: