Developer Application Development: Cast (@strsalary As Decimal (6,2) ) Cast (@strhours As Decimal (6,2) )
Developer Application Development: Cast (@strsalary As Decimal (6,2) ) Cast (@strhours As Decimal (6,2) )
While your primary job as a database developerconsists 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 developmentwith 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
1995 is constant and can never change. This type of value is referred to as deterministic because it
In the same way, a time value such as 5PM is constant and cannot change. There are other values th
in advance because they change based on some circumstances. For example, the starting date of the
from one year to another but it always occurs. This means that, you know it will happen but you d
date. Such a value is referred to as non-deterministic.
To support determinism and non-determinism, Transact-SQL provides two broad categories of funct
always returns the same or known value is referred to as deterministic. A function whose returned val
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 conv
you are expecting. If the value the user provides must be treated as something other than a string
user provides a number, before using such a value, you should first convert it to the appropriate t
string to the expected type.
To assist with conversion, you can use either the CAST() or the CONVERT() function.
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 y
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 mu
multiplication, each is converted to a Decimal type:
Converting a Value
Like CAST(), the CONVERT() function is used to convert a value. Unlike CAST(), CONVERT can b
value its original type into a non-similar type. For example, you can useCONVERT to cast a numb
vice-versa.
The first argument must be a known data type, such as those we reviewed in Lesson 4. If you are
into a string (varchar, nvarchar, char, nchar) or a binary type, you should specify the number of all
data type's own parentheses. As reviewed for the CAST() function, the Expression is the value
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);
GO
String-Based Functions
Introduction
The string is the most basic, the primary value that is presented to a database. This is because, any
treated particularly, is firstly considered a string. In an application, there are various ways you use
can get it or provide it to a function as a constant string, that is, a string whose value you know ce
pass to a function. You can also get a string that a user provides. Other functions also can produce or
To assist you with managing strings or performing operations on them, Transact-SQL provides va
functions can divide in categories that include character-based, conversions, addition, sub-strings, etc
To get the length of a string, you can use the LEN() function. Its syntax is:
int LEN(String)
This function takes one argument as the string to be considered. It returns the number of characters
an example:
int ASCII(String)
This function takes as argument as string and returns the ASCII code of the first (the left) character
an example:
This function takes as argument a numeric value as an integer. Upon conversion, the function
equivalent of that number.
varchar LOWER(String)
This function takes as argument a string. Any lowercase letter that is part of the string would not cha
is part of the string would be converted to lowercase. Any other character or symbol would be
conversion, the LOWER() function returns a new string.
Here is an example:
-- =============================================
-- Function: GetUsername
-- =============================================
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
A left sub-string is one or a group of characters retrieved from the left side of a known string. To get
a string, you can use the LEFT() function. Its syntax is:
This function takes two arguments. The first argument specifies the original string. The second arg
number of characters from the most-left that will constitute the sub-string. After the operation,
returns a new string made of the left character + the NumberOfCharacters on its right from the String
Practical Learning: Creating a Sub-String With Left Characters
1. Delete the previous code from the query window
2. To use the LEFT() function, type the following:
-- =============================================
-- Function: GetUsername
-- =============================================
This function takes two arguments. The first argument specifies the original string. The second arg
number of characters from the most-right that will constitute the sub-string.
-- =============================================
-- Function: Last4DigitsOfSSN
-- =============================================
SELECT Exercise1.dbo.Last4DigitsOfSSN('836483846');
GO
To replace one character or a sub-string from a string, you can use the REPLACE() function. Its synta
or
This function takes three arguments. The first is the string that will be used as refe
argument, FindString, is a character or a sub-string to look for in the String argument. If the FindStri
string is found in the String, then it is replaced with the value of the last argument, ReplaceWith.
-- =============================================
-- Function: Last4DigitsOfSSN
-- =============================================
SELECT Exercise1.dbo.Last4DigitsOfSSN('244-04-8502');
GO
7. Execute the statement in the window
Arithmetic Functions
To find out if a value is positive, null, or negative, Transact-SQL provides the SIGN() function. Its syn
SIGN(Expression)
This function takes as argument a number or an expression that can be evaluated to a number. Th
then examine the number:
-- 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
To get the absolute value of a number, you can use the ABS() function. Its syntax is:
ABS(Expression)
This function takes an expression or a number as argument and returns its absolute value. Here is an
In the same way, consider a number such as –24.06. As this number is negative, it is between –24
being greater.
In algebra, the ceiling of a number is the closest integer that is greater than or higher than the numbe
first case, the ceiling of 12.155 is 13 because 13 is the closest integer greater than or equal to 12.1
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 th
function succeeds, it returns a double-precision number that is greater than or equal to Expression. He
DECLARE @Number1 As Numeric(6, 2),
@Number2 As Numeric(6, 2)
SET @Number1 = 12.155;
SET @Number2 = -24.06;
To support finding the floor of a number, Transact-SQL provides the FLOOR() function. Its syntax is:
FLOOR(Expression)
The FLOOR() function takes as argument a numeric value or an expression that can be evaluated
function succeeds during its conversion, it produces the integer that is the floor of the argument. Here
EXP(Expression)
This function takes one argument as a number or an expression that can be evaluated to a number. H
ReturnValue = xy
To support finding the power of a number, Transact-SQL provides the POWER() function. Its syntax i
POWER(x, y)
This function takes two required arguments. The first argument, x, is used as the base number to
second argument, y, also called the exponent, will raise x to this value. Here is an example:
LOG(Expression)
This function takes one argument as a number or an expression that can evaluate to a number. Aft
returns the natural logarithm of the argument. Here is an example:
LOG10(Expression)
The number to be evaluated is passed as the argument X. The function returns the logarithm on
formula:
y = log10x
which is equivalent to
x = 10y
Here is an example:
SQRT(Expression)
This function takes one argument as a positive decimal number. If the number is positive, after
function returns the square root of x. Here is an example:
In this case, you can use a control statement to find out whether the Expression is positive. Here is an
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
Introduction
A circle is a series of distinct opposite points positioned each at an exact same distance from another
the center. The distance from the center C to one of these equidistant points is called the radius, R. Th
all of the points that are equidistant to the center is called the circumference of the circle. The diam
between two points of the circumference to the center. In other words, a diameter is double the radiu
To manage the measurements and other related operations, the circumference is divided into 360 po
portions is called a degree. The unit used to represent the degree is the degree, written as ˚. Therefo
360 degrees, that is 360˚. The measurement of two points A and D of the circumference could hav
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
ratio of the distance between two points A and B of the circumference divided by the radius R. This ca
PI
The letter п, also written as PI, is a number used in various mathematical calculations. Its ap
3.1415926535897932. The calculator of Microsoft Windows represents it as 3.141592653589793238
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” m
means an angle is not a dimension, it is independent of the size of a circle. Obviously the angle repre
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, Tra
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 radia
A cycle is a measurement of the rotation around the circle. Since the rotation is not necessarily com
the scenario, a measure is made based on the angle that was covered during the rotation. A cycle co
circle, in which case the rotation would not have been completed. A cycle could also cover the who
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
DEGREES(Expression)
This function takes as argument a value in radians. If it succeeds, it returns the equivalent value in de
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
side adjacent to point A. The cosine of the angle at point A is the ratio AC/AB. That is, the ratio of
AC, over the length of the hypotenuse, AB:
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 an
Here is an example:
Consider AB the length of A to B, also called the hypotenuse to point A. Also consider CB the length of
opposite side to point A. The sine represents the ratio of CB/AB; that is, the ratio of the opposit
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 th
between –1 and 1.
Here is an example:
In geometry, consider AC the length of A to C. Also consider BC the length of B to C. The tangent is
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:
Introduction
Date and time values are highly used in database applications. They involve sales, time sheets, taxes,
Based on this usefulness, their operations are supported by various libraries you will be using wh
application. Without being the most elaborate on this issue, Transact-SQL provides its own level of s
time values.
Before using a date or a time value in a calculation, remember that you must first get it one way
define a date or a time constant in your application. An example would be '1992/10/28'. You can dec
a SmallDateTime variable and initialize it as you see fit. You may get a date or a time from another
alternative, you may get a date or time from another application or from a user. Once you have an a
can use it.
To get the current date and the current time of the computer that a user is using, you can use the G
of Transact-SQL. Its syntax is:
GETDATE()
This function simply returns the current date and time of the operating system.
Date/Time Addition
One of the primary operations you may want to perform on a date or a time value would consist of
To support this operation, Transact-SQL provides the DATEADD()function. Its syntax is:
The third argument to this function is the value of a date or a time on which the operation will be pe
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
such as 4.06.
When calling this function, you must first specify the type of value that you want to add. This type i
argument. It is used as follows:
• If you want to add a number of years to a date, specify the TypeOfValue as Year or yy, oryyyy
is case-insensitive). Here is an example:
Type of
Abbreviation As a result
Value
yy
Year A number of years will be added to the date value
yyyy
q
quarter A number of quarters of a year will be added to the date v
qq
m
Month A number of months will be added to the date value
mm
y
dayofyear A number of days of a year will be added to the date value
dy
d
Day A number of days will be added to the date value
dd
wk
Week A number of weeks will be added to the date value
ww
Hour hh A number of hours will be added to the time value
n
minute A number of minutes will be added to the time value
mi
s
second A number of seconds will be added to the time value
ss
millisecond ms 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
the range of two dates or two time values. To support this operation, Transact-SQL provides the DA
Its syntax is:
This function takes three arguments. The second argument is the starting date or the starting time
considered. The third argument is the end or last date or time of the considered range. You use th
specify the type of value you want the function to produce. This argument uses the same
the DATEADD() function:
Type of
Abbreviation As a result
Value
yy The function will return the number of years that have elap
Year
yyyy between the start and the end dates
q The function will return the number of quarters of a year th
quarter
qq have elapsed between the start and the end dates
m The function will return the number of months that have
Month
mm elapsed between the start and the end dates
y The function will return the number of days of a year that
dayofyear
dy elapsed between the start and the end dates
d The function will return the number of days that have elap
Day
dd between the start and the end dates
wk The function will return the number of weeks that have ela
Week
ww between the start and the end dates
The function will return the number of hours that have elap
Hour hh
between the start and the end times or dates
n The function will return the number of minutes that have
minute
mi elapsed between the start and the end times or dates
s The function will return the number of seconds that have
second
ss elapsed between the start and the end times or dates
The function will return the number of milliseconds that ha
millisecond ms
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