Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas...

41
Prentice Hall © 2004 1 Chapter 9: Additional Chapter 9: Additional Functions Functions SQL for SQL Server SQL for SQL Server Bijoy Bordoloi and Douglas Bock Bijoy Bordoloi and Douglas Bock

Transcript of Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas...

Page 1: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 1

Chapter 9: Additional FunctionsChapter 9: Additional Functions

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Page 2: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 2

ObjectivesObjectives

• Use string and text functions to manipulate Use string and text functions to manipulate character and text data.character and text data.

• Use mathematical functions to manipulate Use mathematical functions to manipulate numeric data.numeric data.

• Use conversion functions to convert data Use conversion functions to convert data from one data type to another.from one data type to another.

• Use date/time functions to manipulate Use date/time functions to manipulate date/time data.date/time data.

Page 3: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 3

General NotationGeneral Notation

• Functions are formally defined using the following Functions are formally defined using the following general notation.general notation.

FUNCTION( argument1 FUNCTION( argument1 [,optional_argument2] [,optional_argument2]

[, optional_argument3], … )[, optional_argument3], … )• The function name is in CAPITAL letters.The function name is in CAPITAL letters.• Argument parameters may be filled by either a string of Argument parameters may be filled by either a string of

characters enclosed in single-quote marks, a numeric characters enclosed in single-quote marks, a numeric value, an expression, or a column name.value, an expression, or a column name.

• Some functions require more than one argument and Some functions require more than one argument and some arguments are optional.some arguments are optional.

Page 4: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 4

String and Text FunctionsString and Text Functions

• This category of functions manipulates character This category of functions manipulates character strings and text/image data.strings and text/image data.

• Numbers may be treated as character strings if they Numbers may be treated as character strings if they are not manipulated mathematically.are not manipulated mathematically.

Type of Data to be StoredType of Data to be Stored Example ValuesExample ValuesCustomer Street AddressCustomer Street Address 100 S. Main St.100 S. Main St.Telephone NumberTelephone Number (618) 555-1212(618) 555-1212Customer NameCustomer Name Bijoy BordoloiBijoy BordoloiSocial Security NumberSocial Security Number 999-99-9999999-99-9999Product NumberProduct Number 1239612396

Page 5: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 5

ASCII and CHAR FunctionsASCII and CHAR Functions

• The ASCII function returns the ASCII code value as The ASCII function returns the ASCII code value as an INT numeric value for the left-most character in a an INT numeric value for the left-most character in a character string.character string.

• The character string must be data type CHAR or The character string must be data type CHAR or VARCHAR.VARCHAR.

• The CHAR function returns the ASCII character for The CHAR function returns the ASCII character for an argument of data type INT.an argument of data type INT.

SELECT ASCII('Bijoy') "ASCII", SELECT ASCII('Bijoy') "ASCII", CHAR(98) "Character"CHAR(98) "Character" ASCII Character ASCII Character ----------- --------- ----------- --------- 66 b66 b

Page 6: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 6

UNICODE FunctionUNICODE Function

• This works like the ASCII function but it returns an This works like the ASCII function but it returns an INT value according to the Unicode standard.INT value according to the Unicode standard.

• Unicode strings must be of data type NCHAR or Unicode strings must be of data type NCHAR or NVARCHAR.NVARCHAR.

SELECT UNICODE('$10,000') "Value of $ SELECT UNICODE('$10,000') "Value of $ Sign", UNICODE('₤') "Value of ₤ Sign"Sign", UNICODE('₤') "Value of ₤ Sign"

Value of $ Sign Value of ₤ Sign Value of $ Sign Value of ₤ Sign

--------------- --------------- --------------- ---------------

36 16336 163

Page 7: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 7

STR FunctionSTR Function

• This converts numeric data to a character string and requires a This converts numeric data to a character string and requires a FLOAT data type with a decimal point as a required argument. FLOAT data type with a decimal point as a required argument.

• Two optional arguments: (1) specify the length of the returned Two optional arguments: (1) specify the length of the returned character string and (2) number of digits to the right of the character string and (2) number of digits to the right of the decimal point.decimal point.

SELECT STR(12345.6789,8,2) "Rounded Up",SELECT STR(12345.6789,8,2) "Rounded Up", STR(12345.6744,8,2) "Rounded Down",STR(12345.6744,8,2) "Rounded Down", STR(12345.6789,4,2) "Length Too Short",STR(12345.6789,4,2) "Length Too Short", STR(12345.6789,6) "No Decimal Value";STR(12345.6789,6) "No Decimal Value"; Rounded Up Rounded Down Rounded Up Rounded Down ---------- ---------------------- ------------ 12345.68 12345.67 12345.68 12345.67 Length Too Short No Decimal Value Length Too Short No Decimal Value ---------------- ---------------- ---------------- ---------------- **** 12346**** 12346

Page 8: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 8

Another STR Function ExampleAnother STR Function Example

SELECT STR(emp_salary,7,0) "Salary As String", SELECT STR(emp_salary,7,0) "Salary As String", emp_salary "Salary as Money"emp_salary "Salary as Money"

FROM employee;FROM employee;Salary As String Salary as Money Salary As String Salary as Money ---------------- --------------------- ---------------- --------------------- 30000 30000.000030000 30000.0000 25000 25000.000025000 25000.0000 38000 38000.000038000 38000.0000more rows will be displayed…more rows will be displayed…

Page 9: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 9

LEFT and RIGHT FunctionsLEFT and RIGHT Functions

• These are string extraction functions—they extract These are string extraction functions—they extract substrings from strings.substrings from strings.

• The LEFT returns the left part of a character string The LEFT returns the left part of a character string for the specified number of characters. The for the specified number of characters. The RIGHT returns the right part of a character string.RIGHT returns the right part of a character string.

• The character string argument may be any data The character string argument may be any data type that can be implicitly converted to type that can be implicitly converted to VARCHAR or NVARCHAR, but cannot be VARCHAR or NVARCHAR, but cannot be TEXT or NTEXT. TEXT or NTEXT.

• The integer value must be a positive value that The integer value must be a positive value that specifies the number of characters to extract specifies the number of characters to extract (return) from the character string. (return) from the character string.

Page 10: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 10

LEFT and RIGHT Functions--ExampleLEFT and RIGHT Functions--ExampleSELECT emp_last_name "Full Name", SELECT emp_last_name "Full Name", LEFT(emp_last_name, 5) "First 5", LEFT(emp_last_name, 5) "First 5", RIGHT(emp_last_name, 5) "Last 5"RIGHT(emp_last_name, 5) "Last 5"FROM employee;FROM employee;Full Name First 5 Last 5 Full Name First 5 Last 5 -------------------- ------- ------ -------------------- ------- ------ Bock Bock BockBock Bock BockAmin Amin AminAmin Amin AminJoshi Joshi JoshiJoshi Joshi JoshiZhu Zhu ZhuZhu Zhu ZhuJoyner Joyne oynerJoyner Joyne oynerBordoloi Bordo doloiBordoloi Bordo doloiMarkis Marki arkisMarkis Marki arkisPrescott Presc scott Prescott Presc scott

Page 11: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 11

LEN FunctionLEN Function

• This returns a numeric value equivalent to the number This returns a numeric value equivalent to the number of characters in a specified character string. Trailing of characters in a specified character string. Trailing blanks are ignored.blanks are ignored.

• It is useful for determining the amount of space to be It is useful for determining the amount of space to be allocated for an output column in a report.allocated for an output column in a report.

SELECT DISTINCT emp_city "City", SELECT DISTINCT emp_city "City", LEN(emp_city) "Length" FROM employee;LEN(emp_city) "Length" FROM employee; City Length City Length ------------------------- ----------- ------------------------- ----------- Collinsville 12Collinsville 12 Edwardsville 12Edwardsville 12 Marina 6Marina 6 Monterey 8Monterey 8

Page 12: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 12

LTRIM and RTRIM FunctionsLTRIM and RTRIM Functions• These functions trim leading and trailing characters from These functions trim leading and trailing characters from

CHAR data columns.CHAR data columns.• CHAR data columns are automatically blank-padded CHAR data columns are automatically blank-padded

when values are not sufficiently large to fill up all of the when values are not sufficiently large to fill up all of the column space—concatenating the columns causes a column space—concatenating the columns causes a display with too much blank space.display with too much blank space.

SELECT drug_name+drug_unit "Drug", SELECT drug_name+drug_unit "Drug", RTRIM(drug_name)+' '+RTRIM(drug_unit)RTRIM(drug_name)+' '+RTRIM(drug_unit) "Concatenated" FROM drug_table;"Concatenated" FROM drug_table; Drug Concatenated Drug Concatenated ------------------ ----------------- ------------------ ----------------- Aspirin 25 mg Aspirin 25 mgAspirin 25 mg Aspirin 25 mg Toprol 0.05 mg Toprol 0.05 mgToprol 0.05 mg Toprol 0.05 mg Ibuprofen 800 mg Ibuprofen 800 mgIbuprofen 800 mg Ibuprofen 800 mg

Page 13: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 13

UPPER and LOWER FunctionsUPPER and LOWER Functions

• These alter the appearance of information displayed These alter the appearance of information displayed by converting string data to either upper or lower case by converting string data to either upper or lower case characters.characters.SELECT LOWER(emp_gender) "Gender", SELECT LOWER(emp_gender) "Gender", UPPER(emp_last_name) "Last Name"UPPER(emp_last_name) "Last Name"FROM employee;FROM employee;Gender Last Name Gender Last Name ------ ------------------------- ------ ------------------------- m BOCKm BOCKm AMINm AMINm JOSHIm JOSHImore rows will be displayed…more rows will be displayed…

Page 14: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 14

Combining and Embedding Functions Combining and Embedding Functions

• The State column data is stored as 2-character The State column data is stored as 2-character capitalized abbreviations for state names.capitalized abbreviations for state names.

SELECT LTRIM(emp_last_name) "Last Name", SELECT LTRIM(emp_last_name) "Last Name", UPPER(LEFT(emp_state,1)) + UPPER(LEFT(emp_state,1)) + LOWER(RIGHT(emp_state,1)) "State"LOWER(RIGHT(emp_state,1)) "State"

FROM employee;FROM employee;Last Name State Last Name State ------------------------- ----- ------------------------- ----- Bock MoBock MoAmin CaAmin CaJoshi IlJoshi Il

Page 15: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 15

CHARINDEX FunctionCHARINDEX Function

• This returns the INT value for the starting position This returns the INT value for the starting position of a substring in a string—a kind of search of a substring in a string—a kind of search function to confirm the existence of a substring.function to confirm the existence of a substring.

• The first string argument is the substring to be The first string argument is the substring to be found in the second character string argument. found in the second character string argument.

• The second character string argument is usually The second character string argument is usually expressed as a column from a table. expressed as a column from a table.

• The start position argument is optional and can be The start position argument is optional and can be used to specify a character position starting point used to specify a character position starting point for the search. for the search.

• A value of 0 (zero) is returned if the substring is A value of 0 (zero) is returned if the substring is not found.not found.

Page 16: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 16

CHARINDEX Function—Example CHARINDEX Function—Example

• This lists all employees that live on High St. by searching This lists all employees that live on High St. by searching the the emp_addressemp_address column (substring is not equal to zero). column (substring is not equal to zero).

SELECT RTRIM(emp_last_name) + ', ' + SELECT RTRIM(emp_last_name) + ', ' + RTRIM(emp_first_name) "Employee",RTRIM(emp_first_name) "Employee",

emp_address "Address" emp_address "Address" FROM employeeFROM employeeWHERE CHARINDEX('High St', emp_address) != 0;WHERE CHARINDEX('High St', emp_address) != 0;Employee Address Employee Address ---------------- ------------------------------------- ---------------------Markis, Marcia High St. #14Markis, Marcia High St. #14

Page 17: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 17

REPLACE FunctionREPLACE Function

• This scans a character string and replaces a character substring This scans a character string and replaces a character substring with another specified character substring. Here we replace with another specified character substring. Here we replace the acronym ER with the words “Emergency Room.”the acronym ER with the words “Emergency Room.”

SELECT REPLACE(note_comment, 'ER', 'Emergency room') "Note SELECT REPLACE(note_comment, 'ER', 'Emergency room') "Note Comment“ Comment“

FROM patient p INNER JOIN patient_note pn FROM patient p INNER JOIN patient_note pn ON p.pat_id = pn.pat_idON p.pat_id = pn.pat_idWHERE CHARINDEX('admitted from ER', note_comment) WHERE CHARINDEX('admitted from ER', note_comment) != 0;!= 0;Patient Note Comment Patient Note Comment

--------------- ----------------------------------------------------- --------------------------------------Howard, Ronald Patient admitted from Emergency roomHoward, Ronald Patient admitted from Emergency roomMore rows will be displayed...More rows will be displayed...

Page 18: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 18

SUBSTRING FunctionSUBSTRING Function

• A very powerful function to extract a substring A very powerful function to extract a substring from a string—used to display portions of large from a string—used to display portions of large text character strings.text character strings.

• Works with character, binary, text, or image data.Works with character, binary, text, or image data.• There are three required arguments—argument #1 There are three required arguments—argument #1

is the character string, argument #2 is an INT is the character string, argument #2 is an INT value specifying the start position to extract, and value specifying the start position to extract, and argument #3 specifies the number of characters to argument #3 specifies the number of characters to be extracted.be extracted.

Page 19: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 19

SUBSTRING Function—Example #1 SUBSTRING Function—Example #1

• This example extracts the last four digits of each This example extracts the last four digits of each employee’s social security number.employee’s social security number.

SELECT RTRIM(emp_last_name) + ', ' +SELECT RTRIM(emp_last_name) + ', ' + RTRIM(emp_first_name) "Employee",RTRIM(emp_first_name) "Employee", SUBSTRING(emp_ssn,6,4) "Last 4 SSN"SUBSTRING(emp_ssn,6,4) "Last 4 SSN"FROM employeeFROM employeeWHERE emp_dpt_number = 3;WHERE emp_dpt_number = 3;Employee Last 4 SSN Employee Last 4 SSN ----------------------- ---------- ----------------------- ---------- Amin, Hyder 2222Amin, Hyder 2222Joyner, Suzanne 5555Joyner, Suzanne 5555

Markis, Marcia 7777Markis, Marcia 7777

Page 20: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 20

SUBSTRING Function—Example #2SUBSTRING Function—Example #2

• This formats the SSN by inserting dash symbols.This formats the SSN by inserting dash symbols.

SELECT emp_last_name+', '+emp_first_name SELECT emp_last_name+', '+emp_first_name "Employee ", "Employee ", SUBSTRING(emp_ssn,1,3)+'-'+SUBSTRING(emp_sSUBSTRING(emp_ssn,1,3)+'-'+SUBSTRING(emp_ssn,4,2)+'-'+sn,4,2)+'-'+

SUBSTRING(emp_ssn,6,4) "SSN"SUBSTRING(emp_ssn,6,4) "SSN"FROM employeeFROM employeeWHERE emp_dpt_number = 3;WHERE emp_dpt_number = 3;Employee SSN Employee SSN ----------------------- ----------- ----------------------- ----------- Amin, Hyder 999-22-2222Amin, Hyder 999-22-2222Joyner, Suzanne 999-55-5555Joyner, Suzanne 999-55-5555

Page 21: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 21

Mathematical FunctionsMathematical Functions

• This category of functions manipulates This category of functions manipulates values stored as numeric data.values stored as numeric data.

• Aggregate numeric functions were covered Aggregate numeric functions were covered in Chapter 5.in Chapter 5.

• This chapter focuses on functions that act This chapter focuses on functions that act on single numeric values and those that on single numeric values and those that perform special mathematical perform special mathematical manipulations.manipulations.

Page 22: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 22

Single-Value FunctionsSingle-Value Functions

• These functions can be combined with the These functions can be combined with the arithmetic operator symbols (+ - * / %) to arithmetic operator symbols (+ - * / %) to develop complex expressions.develop complex expressions.

• Numeric functions accept numeric Numeric functions accept numeric arguments – column names that are defined arguments – column names that are defined as numeric data types and expressions – as numeric data types and expressions – they return numeric values – the type of they return numeric values – the type of data returned varies.data returned varies.

Page 23: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 23

Transcendental FunctionsTranscendental Functions• These include single value functions: ACOS, These include single value functions: ACOS,

ASIN, ATAN, ATAN2, COS, EXP, LOG, LOG10, ASIN, ATAN, ATAN2, COS, EXP, LOG, LOG10, SIN, and TAN.SIN, and TAN.

• We will not focus on most of these as they are We will not focus on most of these as they are rarely used in business except for the financial and rarely used in business except for the financial and marketing research areas.marketing research areas.

SELECT COS(0.5) "COS", EXP(1) "EXP", SELECT COS(0.5) "COS", EXP(1) "EXP", LOG(0.5) "LOG", LOG10(0.5) "LOG10";LOG(0.5) "LOG", LOG10(0.5) "LOG10";COS EXP LOG LOG10 COS EXP LOG LOG10

-------- --------- ---------- ---------- -------- --------- ---------- ---------- 0.877582 2.7182818 -0.6931472 -0.30103000.877582 2.7182818 -0.6931472 -0.3010300more precision is displayed with SQL Query more precision is displayed with SQL Query AnalyzerAnalyzer

Page 24: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 24

ISNULL FunctionISNULL Function

• This function allows you to deal with situations where This function allows you to deal with situations where data columns have NULL values. data columns have NULL values.

• The function works with numeric, character, date, and The function works with numeric, character, date, and other data types. If the other data types. If the check_expressioncheck_expression argument is argument is NULL, the ISNULL function returns the NULL, the ISNULL function returns the replacement_valuereplacement_value argument. argument.

• The query on the next slide shows a result requested by The query on the next slide shows a result requested by a senior project manager by listing a value of 0.0 where a senior project manager by listing a value of 0.0 where the the work_hourswork_hours column is NULL. column is NULL.

Page 25: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 25

ISNULL Function—ExampleISNULL Function—Example SELECT work_emp_ssn "SSN", work_pro_number SELECT work_emp_ssn "SSN", work_pro_number "Project", ISNULL(work_hours, 0) "Hours""Project", ISNULL(work_hours, 0) "Hours"

FROM assignmentFROM assignmentWHERE work_pro_number IN (1,20);WHERE work_pro_number IN (1,20);

SSN Project Hours SSN Project Hours --------- ------- ------- --------- ------- ------- 999111111 1 31.4999111111 1 31.4 999444444 1 .0999444444 1 .0 999444444 20 11.8999444444 20 11.8 999555555 20 14.8999555555 20 14.8 999666666 20 .0999666666 20 .0 999888888 1 21.0999888888 1 21.0

Page 26: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 26

ABS FunctionABS Function• This returns the absolute value as a measure of This returns the absolute value as a measure of

magnitude, and works for a numeric value or magnitude, and works for a numeric value or expression.expression.

• This example shows the difference in work reported This example shows the difference in work reported from the 20 hours established as the desired standard.from the 20 hours established as the desired standard.

SELECT work_emp_ssn "SSN", work_pro_number SELECT work_emp_ssn "SSN", work_pro_number "Project #", work_hours "Worked", "Project #", work_hours "Worked", ABS(work_hours - 20) "Difference"ABS(work_hours - 20) "Difference"

FROM assignmentFROM assignmentWHERE ABS(work_hours - 20) >= 10WHERE ABS(work_hours - 20) >= 10ORDER BY ABS(work_hours - 20);ORDER BY ABS(work_hours - 20);SSN Project # Worked Difference SSN Project # Worked Difference --------- --------- --------- ---------- --------- --------- --------- ---------- 999887777 30 30.8 10.8999887777 30 30.8 10.8999111111 1 31.4 11.4999111111 1 31.4 11.4

Page 27: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 27

POWER, SQRT, SQUARE and ROUNDPOWER, SQRT, SQUARE and ROUND

• POWER raises a numeric argument to a specified POWER raises a numeric argument to a specified positive exponent.positive exponent.

• SQUARE squares FLOAT numeric values – this SQUARE squares FLOAT numeric values – this is equivalent to POWER(is equivalent to POWER(numbernumber, 0.5)., 0.5).

• SQRT takes the square root of a FLOAT value.SQRT takes the square root of a FLOAT value.

SELECT POWER(25.0, 3.0) "Cubed", SELECT POWER(25.0, 3.0) "Cubed", POWER(25.0, 0.5) "0.5 Power", POWER(25.0, 0.5) "0.5 Power", SQRT(25) "Square Root", SQUARE(25.0) SQRT(25) "Square Root", SQUARE(25.0) "Squared";"Squared";

Cubed 0.5 Power Square Root SquaredCubed 0.5 Power Square Root Squared--------- ---------- ----------- ----------------- ---------- ----------- --------15625.0 5.0 5.0 625.015625.0 5.0 5.0 625.0

Page 28: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 28

ROUND FunctionROUND Function

• This rounds numeric values to specific levels of This rounds numeric values to specific levels of mathematical precision – two arguments are needed: the mathematical precision – two arguments are needed: the value to round and a value representing the precision.value to round and a value representing the precision.

SELECT work_emp_ssn "SSN", work_hours "Hours", SELECT work_emp_ssn "SSN", work_hours "Hours", ROUND(work_hours,0) "Rounded to 0",ROUND(work_hours,0) "Rounded to 0", ROUND(work_hours,-1) "Rounded to 10"ROUND(work_hours,-1) "Rounded to 10"FROM assignment ORDER BY work_emp_ssn;FROM assignment ORDER BY work_emp_ssn;SSN Hours Rounded to 0 Rounded to 10 SSN Hours Rounded to 0 Rounded to 10 --------- ----- ------------ ------------- --------- ----- ------------ ------------- 999111111 31.4 31.0 30.0999111111 31.4 31.0 30.0999111111 8.5 9.0 10.0999111111 8.5 9.0 10.0999222222 34.5 35.0 30.0999222222 34.5 35.0 30.0

Page 29: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 29

Conversion FunctionsConversion Functions

• These convert values of one data type to These convert values of one data type to another data type.another data type.

• This is termed explicit casting or This is termed explicit casting or conversion.conversion.

• SQL Server also supports implicit casting, SQL Server also supports implicit casting, which is the automatic conversion among which is the automatic conversion among data types.data types.

Page 30: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 30

CONVERT FunctionCONVERT Function• This supports any SQL Server data type. You can use This supports any SQL Server data type. You can use

CONVERT in both SELECT and WHERE clauses.CONVERT in both SELECT and WHERE clauses.• Argument 1 is the data type to convert to and argument Argument 1 is the data type to convert to and argument

2 is the value to be converted. Both are required. 2 is the value to be converted. Both are required. Argument 3 is optional and specifies a display style for Argument 3 is optional and specifies a display style for output formatting through the use of style codes.output formatting through the use of style codes.

SELECT CONVERT(CHAR(12), emp_last_name+', SELECT CONVERT(CHAR(12), emp_last_name+', '+emp_first_name) "Name“ FROM employee;'+emp_first_name) "Name“ FROM employee;

Name Name ------------ ------------ Bock, DouglaBock, Dougla Amin, Hyder Amin, Hyder Joshi, DinesJoshi, Dines

Page 31: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 31

CONVERT Function—Example 2CONVERT Function—Example 2

• This displays employee last name and first initial.This displays employee last name and first initial.

SELECT emp_last_name + ', SELECT emp_last_name + ',

'+CONVERT(CHAR(1), emp_first_name)'+CONVERT(CHAR(1), emp_first_name)

+'.' "Name"+'.' "Name"

FROM employee;FROM employee;

Name Name

----------------------------- -----------------------------

Bock, D.Bock, D.

Amin, H.Amin, H.

Joshi, D.Joshi, D.

Page 32: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 32

CONVERT Function—Example 3CONVERT Function—Example 3• This converts the emp_date_of_birth column (a This converts the emp_date_of_birth column (a

DATETIME data type) to CHAR for display formatted DATETIME data type) to CHAR for display formatted using the style parameter code of 107.using the style parameter code of 107.

SELECT CONVERT(CHAR(15), SELECT CONVERT(CHAR(15), RTRIM(emp_last_name) + ', ' +RTRIM(emp_last_name) + ', ' + RTRIM(emp_first_name)) "Employee",RTRIM(emp_first_name)) "Employee", CONVERT(CHAR(15), emp_date_of_birth,CONVERT(CHAR(15), emp_date_of_birth, 107) "Birthday"107) "Birthday" FROM employee;FROM employee; Employee Birthday Employee Birthday --------------- --------------- --------------- --------------- Bock, Douglas Dec 05, 1950 Bock, Douglas Dec 05, 1950 Amin, Hyder Mar 29, 1969 Amin, Hyder Mar 29, 1969 Joshi, Dinesh Sep 15, 1972Joshi, Dinesh Sep 15, 1972

Page 33: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 33

CAST FunctionCAST Function

• This works identical to the CONVERT except CAST This works identical to the CONVERT except CAST does not support the style argument. The syntax is does not support the style argument. The syntax is different and uses the keyword AS to specify the data different and uses the keyword AS to specify the data type.type.

SELECT CAST(emp_last_name+',SELECT CAST(emp_last_name+', '+emp_first_name AS CHAR(12)) "Name"'+emp_first_name AS CHAR(12)) "Name" FROM employee;FROM employee; Name Name ------------ ------------ Bock, DouglaBock, Dougla Amin, Hyder Amin, Hyder Joshi, DinesJoshi, Dines

Page 34: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 34

DATE FunctionsDATE Functions

• The DATETIME and SMALLDATETIME The DATETIME and SMALLDATETIME data types store both date and time data types store both date and time information.information.

• The DATETIME data type stores more The DATETIME data type stores more accuracy (to 3.33 milliseconds) and a wider accuracy (to 3.33 milliseconds) and a wider range of dates.range of dates.

• The DATE functions enable mathematical The DATE functions enable mathematical manipulation of dates.manipulation of dates.

Page 35: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 35

GETDATE and GETUTCDATE FunctionsGETDATE and GETUTCDATE Functions

• GETDATE returns the current operating system GETDATE returns the current operating system date and time while GETUTCDATE returns this date and time while GETUTCDATE returns this value using the Universal Time Coordinate value using the Universal Time Coordinate (Greenwich Mean Time).(Greenwich Mean Time).

SELECT GETDATE() "Current Date and Time";SELECT GETDATE() "Current Date and Time";

Current Date and Time Current Date and Time

------------------------- -------------------------

2003-02-06 19:22:08.153 2003-02-06 19:22:08.153

Page 36: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 36

DatePart TableDatePart Table

• DatePartDatePart is an argument parameter used in several date is an argument parameter used in several date functions. This specifies the part of a date to return by a functions. This specifies the part of a date to return by a function. The argument also has accepted abbreviations.function. The argument also has accepted abbreviations.

DatepartDatepart Abbrev.Abbrev. DatepartDatepart Abbrev.Abbrev.YearYear yy, yyyyyy, yyyy DayDay dd, ddd, dQuarterQuarter qq, qqq, q HourHour hhhhMonthMonth mm, mmm, m MinuteMinute mi, nmi, nDay of yearDay of year dy, ydy, y SecondSecond ss, sss, sWeekWeek wk, wwwk, ww Millisecond msMillisecond msDay of week*Day of week* dwdw *not accepted for datepart – use the *not accepted for datepart – use the abbreviation.abbreviation.

Page 37: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 37

Date Arithmetic – the DATEADD FunctionDate Arithmetic – the DATEADD Function

• DATEADD takes three arguments – the DATEADD takes three arguments – the DatePartDatePart argument, the value to add (as a number), and the value argument, the value to add (as a number), and the value that is being modified (usually a column value or that is being modified (usually a column value or expression that is a date data type).expression that is a date data type).

SELECT CONVERT(CHAR(15), RTRIM(emp_last_name) SELECT CONVERT(CHAR(15), RTRIM(emp_last_name) + ', ' +RTRIM(emp_first_name)) "Employee",+ ', ' +RTRIM(emp_first_name)) "Employee",

DATEADD(year, 65, emp_date_of_birth) "Date DATEADD(year, 65, emp_date_of_birth) "Date Turns 65"Turns 65"

FROM employee;FROM employee;Employee Date Turns 65 Employee Date Turns 65 --------------- ----------------------- --------------- ----------------------- Bock, Douglas 2015-12-05 00:00:00.000Bock, Douglas 2015-12-05 00:00:00.000Amin, Hyder 2034-03-29 00:00:00.000Amin, Hyder 2034-03-29 00:00:00.000

Page 38: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 38

Date Arithmetic – the DATEDIFF FunctionDate Arithmetic – the DATEDIFF Function

• DATEDIFF performs date subtraction by DATEDIFF performs date subtraction by subtracting two date column values to produce the subtracting two date column values to produce the number of years, quarters, months, and so on. number of years, quarters, months, and so on. between two dates. Use between two dates. Use DatePartDatePart as a parameter as a parameter to specify the type of difference to take.to specify the type of difference to take.

• The first parameter is the The first parameter is the DatePartDatePart argument. argument. • The second parameter is the The second parameter is the start_datestart_date..• The third parameter is the The third parameter is the end_dateend_date..

Page 39: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 39

DATEDIFF Function—ExampleDATEDIFF Function—Example

• This displays the number of months the manager of This displays the number of months the manager of department 3 has worked in his position.department 3 has worked in his position.

SELECT dpt_mgrssn "SSN", emp_last_name SELECT dpt_mgrssn "SSN", emp_last_name "Last Name", DATEDIFF(mm, dpt_mgr_start_date, "Last Name", DATEDIFF(mm, dpt_mgr_start_date, GETDATE()) "Number of Months"GETDATE()) "Number of Months"

FROM department d INNER JOIN employee e FROM department d INNER JOIN employee e ON d.dpt_mgrssn = e.emp_ssnON d.dpt_mgrssn = e.emp_ssnWHERE dpt_no = 3;WHERE dpt_no = 3;SSN Last Name Number of Months SSN Last Name Number of Months --------- ------------- ---------------- --------- ------------- ---------------- 999555555 Joyner 25999555555 Joyner 25Your answer will vary depending on when you Your answer will vary depending on when you execute the query.execute the query.

Page 40: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 40

DATENAME, DAY, MONTH, and YEAR FunctionsDATENAME, DAY, MONTH, and YEAR Functions• DATENAME requires the DatePart argument DATENAME requires the DatePart argument

and the date to be displayed as a name. DAY, and the date to be displayed as a name. DAY, MONTH, and YEAR require a date argument MONTH, and YEAR require a date argument and return an INT.and return an INT.

SELECT CAST(emp_last_name AS CHAR(12)) "Last SELECT CAST(emp_last_name AS CHAR(12)) "Last Name", CAST(DATENAME(mm, emp_date_of_birth) Name", CAST(DATENAME(mm, emp_date_of_birth)

AS CHAR(12)) "Month Born", AS CHAR(12)) "Month Born", DAY(emp_date_of_birth) "Day Born",DAY(emp_date_of_birth) "Day Born", MONTH(emp_date_of_birth) "Month",MONTH(emp_date_of_birth) "Month", YEAR(emp_date_of_birth) "Year"YEAR(emp_date_of_birth) "Year"FROM employee;FROM employee;Last Name Month Born Day Born Month Year Last Name Month Born Day Born Month Year --------- ---------- -------- ----- ---- --------- ---------- -------- ----- ---- Bock December 5 12 1950Bock December 5 12 1950

Page 41: Prentice Hall © 20041 Chapter 9: Additional Functions SQL for SQL Server Bijoy Bordoloi and Douglas Bock.

Prentice Hall © 2004 41

SummarySummary

• Additional functions add power to SQL queries.Additional functions add power to SQL queries.

• The Character functions manipulate character data. Two The Character functions manipulate character data. Two important functions are CHARINDEX for searching strings and important functions are CHARINDEX for searching strings and SUBSTRING for extracting substrings.SUBSTRING for extracting substrings.

• Mathematical Functions manipulate numeric data types and Mathematical Functions manipulate numeric data types and include the transcendental functions for financial and marketing include the transcendental functions for financial and marketing research business applications.research business applications.

• The ISNULL function substitutes values where NULLs are The ISNULL function substitutes values where NULLs are stored.stored.

• CONVERT and CAST convert data from one data type to CONVERT and CAST convert data from one data type to another.another.

• Date functions generate system dates and enable date arithmetic Date functions generate system dates and enable date arithmetic as well as the extraction and display of date data.as well as the extraction and display of date data.