prentice hall © 20041 cos 346 day 15. 7-2 agenda questions?questions? assignment 6 not...

80
Prentice Hall © 2004 1 COS 346 COS 346 Day 15 Day 15

Upload: preston-oconnor

Post on 17-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 1

COS 346COS 346

Day 15Day 15

Page 2: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

7-2

AgendaAgenda

• Questions?Questions?• Assignment 6 Not corrected Assignment 6 Not corrected • Assignment 7 Posted Assignment 7 Posted

– Due March 30Due March 30• Assignment 8 posted Assignment 8 posted • New Time line New Time line • More on SQL & SQL ServerMore on SQL & SQL Server

– Chap 8 & 9 Chap 8 & 9 – Joins & Subqueries Joins & Subqueries

Page 3: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

New time lineNew time line

• MarchMarch

– 26 - SQL 8 & 926 - SQL 8 & 9

– 30 - SQL 1030 - SQL 10

• Assignment 7 dueAssignment 7 due

• Progress reportProgress report

• AprilApril

– 2 Database Redesign 2 Database Redesign – 6 - 6 - Database redesign Database redesign

• Quiz 2Quiz 2

• Assignment 8 due Assignment 8 due

– 9 - Managing Multiuser databases 9 - Managing Multiuser databases

– 13 - Managing Multiuser 13 - Managing Multiuser databases databases

• Assignment 9 due Assignment 9 due

– 16 Managing Multiuser databases 16 Managing Multiuser databases

– 20 Database access standards20 Database access standards

• Progress report Progress report

– 23 - Database access standards23 - Database access standards

• Assignment 10 dueAssignment 10 due

– 2727

• Quiz 3Quiz 3

• Capstones Presentations Due Capstones Presentations Due

Page 4: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Chapter 8: Views and Tables with Chapter 8: Views and Tables with IdentityIdentity

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

Page 5: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

ObjectivesObjectives• Create a single table view.• Create a join table view—include functions.• Insert, update, and delete table rows using a view.• Create a view with errors.• Drop a view.• Create a table with column specifications that

include the identity property.• Insert data rows into tables with a column

specified with the identity property.• Use SCOPE_IDENTITY function to insert data

rows into tables related to a table that has a column specified with the identity property.

Page 6: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

VIEWSVIEWS• A database view is a A database view is a logical logical oror virtual table virtual table based on based on

a query. It is useful to think of a a query. It is useful to think of a viewview as a stored as a stored query that can contain columns from one or more query that can contain columns from one or more tables.tables.

Page 7: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

VIEWS Cont.VIEWS Cont.

• Views are created through use of a CREATE Views are created through use of a CREATE VIEW command that incorporates use of the VIEW command that incorporates use of the SELECT statement. SELECT statement.

• Views are queried just like tables—to a Views are queried just like tables—to a system user, they appear to be tables. system user, they appear to be tables.

• View definitions and execution plans are View definitions and execution plans are stored in the SQL Server database – the data stored in the SQL Server database – the data for a view is gathered each time a view is for a view is gathered each time a view is queried.queried.

Page 8: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

VIEWS Cont.VIEWS Cont.

• Why use views?Why use views?– Views are simple to use.Views are simple to use.– Views enable a system designer to custom Views enable a system designer to custom

model data in a database – a user’s “view.”model data in a database – a user’s “view.”– They provide a form of security by limiting They provide a form of security by limiting

access to columns certain employees need to access to columns certain employees need to access while other data, such as employee access while other data, such as employee salary figures are hidden.salary figures are hidden.

– Views can also be used to update one or more Views can also be used to update one or more tables.tables.

Page 9: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

An Example CREATE VIEW CommandAn Example CREATE VIEW Command

• The columns are renamed from the table The columns are renamed from the table column names to match the way that system column names to match the way that system users think about the data. users think about the data.

/* SQL Example 8.1 */

CREATE VIEW employee_parking

(parking_space, last_name,

first_name, ssn) AS

SELECT emp_parking_space, emp_last_name,

emp_first_name, emp_ssn

FROM employee

Page 10: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Page 11: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Selecting from a ViewSelecting from a View

• Notice that the only columns in the query are those Notice that the only columns in the query are those defined as part of the view. Also, a view can be sorted defined as part of the view. Also, a view can be sorted with the ORDER BY clause just like a table.with the ORDER BY clause just like a table.

/* SQL Example 8.2 */ SELECT * FROM employee_parking ORDER BY last_name, first_name;

parking_space last_name first_name ssn ––––-–––––––––– –––––––-––– -––––––––-––– –––––––-– 422 Amin Hyder 999222222 542 Bock Douglas 999111111 1 Bordoloi Bijoy 999666666 more rows will be displayed . . .

  

Page 12: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Page 13: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

CREATE VIEW SyntaxCREATE VIEW Syntax

• The general syntax has several options as The general syntax has several options as shown here.shown here.

CREATE VIEW [ <database_name>.]

[< owner>.] view_name

[(column_name1 [,column_name2 ...

column_name_n ] ) ]

[WITH <view_attribute1>

[, view_attribute2,…view_attribute_n] ]

AS

SELECT

[ WITH CHECK OPTION ]

Page 14: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

View Syntax RulesView Syntax Rules

• The database name and owner name specification The database name and owner name specification is optional.is optional.

• View names must comply with SQL Server View names must comply with SQL Server naming rules.naming rules.

• Columns included in a view can be optionally Columns included in a view can be optionally renamed. Renaming is required if:renamed. Renaming is required if:– a column is derived by an arithmetic expression, a column is derived by an arithmetic expression,

function, or constant.function, or constant.

– a JOIN causes the selection of two column from a JOIN causes the selection of two column from different tables with the same name—rename one of different tables with the same name—rename one of the columns.the columns.

Page 15: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

View Syntax Rules Contd.View Syntax Rules Contd.• The AS keyword is required.The AS keyword is required.• The SELECT statement defines the columns in a The SELECT statement defines the columns in a

view.view.• The SELECT can select from one or more tables The SELECT can select from one or more tables

including a JOIN operation or select columns from including a JOIN operation or select columns from other views.other views.

• The SELECT cannot include:The SELECT cannot include:– COMPUTE or COMPUTE BY clauses.COMPUTE or COMPUTE BY clauses.– ORDER BY clauses unless TOP is used.ORDER BY clauses unless TOP is used.– The INTO keyword.The INTO keyword.– A temporary table or table variable.A temporary table or table variable.– More than 1,024 columns.More than 1,024 columns.

Page 16: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Example CREATE VIEW with Columns RenamedExample CREATE VIEW with Columns Renamed

/* SQL Example 8.3 */CREATE VIEW empview7 (SSN, FirstName, LastName, Dept) ASSELECT emp_ssn, emp_first_name, emp_last_name, emp_dpt_numberFROM employeeWHERE emp_dpt_number=7WITH CHECK OPTION

Page 17: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Selecting from Empview7Selecting from Empview7• The column names from the view are probably more The column names from the view are probably more

meaningful to system users than the original meaningful to system users than the original employeeemployee table column names.table column names.

/* SQL Example 8.4 */

SELECT *

FROM empview7;

SSN FirstName LastName Dept

––––––––– –––––––––--––––– ––––--––––––––– –––––

999111111 Douglas Bock 7

999333333 Dinesh Joshi 7

999444444 Waiman Zhu 7

999888888 Sherri Prescott 7

Page 18: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

A View with the Same Structure as a TableA View with the Same Structure as a Table

• The column names are more meaningful.The column names are more meaningful.• The manager’s SSN is already formatted.The manager’s SSN is already formatted.

/* SQL Example 8.5 */

CREATE VIEW dept_view (DepartmentNo,

Name, ManagerSSN, StartDate) AS

SELECT dpt_no, dpt_name,

LEFT(dpt_mgrssn,3)+'-'

+SUBSTRING(dpt_mgrssn,4,2)+'-'+

RIGHT(dpt_mgrssn,4),

CAST(dpt_mgr_start_date As CHAR(11))

FROM department

Page 19: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Selecting from the Dept_ViewSelecting from the Dept_View

/* SQL Example 8.6 */

SELECT *

FROM dept_view;

DepartmentNo Name ManagerSSN StartDate

–––––––––––— –––—–––––––—–––––– ––––––––––– –––––––––––

1 Headquarters 999-66-6666 Jun 19 1981

3 Admin and Records 999-55-5555 Jan 1 2001

7 Production 999-44-4444 May 22 1998

Page 20: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

FUNCTIONS AND VIEWS:FUNCTIONS AND VIEWS:JOIN VIEWSJOIN VIEWS

• Views can contain simple row functions and Views can contain simple row functions and also JOIN tables.also JOIN tables.

/* SQL Example 8.8 */

CREATE VIEW dept_salary

(Name, MinSalary, MaxSalary, AvgSalary) AS

SELECT d.dpt_name, MIN(e.emp_salary),

MAX(e.emp_salary), AVG(e.emp_salary)

FROM employee e JOIN department d ON

(e.emp_dpt_number=d.dpt_no)

GROUP BY d.dpt_name

Page 21: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Selecting from the Dept_Salary ViewSelecting from the Dept_Salary View /* SQL Example 8.9 */ SELECT * FROM dept_salary;

Name MinSalary MaxSalary AvgSalary ––––––––––––––––— ––––——––-–– ––––––-–––– ––––––-––– Admin and Records 25000.0000 43000.0000 31000.0000 Headquarters 55000.0000 55000.0000 55000.0000 Production 25000.0000 43000.0000 34000.0000

Page 22: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

DROPPING VIEWSDROPPING VIEWS

• A Database Administrator or View Owner A Database Administrator or View Owner can drop a view with the DROP VIEW can drop a view with the DROP VIEW statement.statement.

/* SQL Example 8.10 */

DROP VIEW dept_view;

Page 23: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

View StabilityView Stability

• Views do not store data – only the view definition Views do not store data – only the view definition is stored, and view data is only temporary.is stored, and view data is only temporary.

• When a table underlying a view is dropped, the When a table underlying a view is dropped, the view becomes invalid.view becomes invalid.

• The server message for a SELECT from an invalid The server message for a SELECT from an invalid view is: view is: Msg 208, Procedure <view Msg 208, Procedure <view name>, Line #, Invalid Object name>, Line #, Invalid Object <table name>.<table name>.

• If the table is recreated, the view will again work If the table is recreated, the view will again work satisfactorily.satisfactorily.

Page 24: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

INSERTING, UPDATING, and INSERTING, UPDATING, and DELETING ROWS THROUGH VIEWSDELETING ROWS THROUGH VIEWS

• Inserting and updating table rows through views is Inserting and updating table rows through views is complex; deleting rows is simpler.complex; deleting rows is simpler.

• To execute DML on a view, the view must be To execute DML on a view, the view must be updateable:updateable:– No aggregate functions are specified in the SELECT No aggregate functions are specified in the SELECT

list.list.– Cannot use the TOP, GROUP BY, DISTINCT, or Cannot use the TOP, GROUP BY, DISTINCT, or

UNION clauses.UNION clauses.– No derived columns in the SELECT list.No derived columns in the SELECT list.– Views created with a JOIN can only modify or insert Views created with a JOIN can only modify or insert

rows in one table at a time.rows in one table at a time.

Page 25: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Inserting RowsInserting Rows• The INSERT statement cannot violate any constraints on The INSERT statement cannot violate any constraints on

underlying tables.underlying tables.

• Here, the Here, the departmentdepartment table has four columns and the view only table has four columns and the view only has two columns, but the other two table columns can be has two columns, but the other two table columns can be

NULL.NULL. /* SQL Example 8.21 */

CREATE VIEW dept_view2 AS

SELECT dpt_no, dpt_name

FROM department

/* SQL Example 8.22 */

INSERT INTO dept_view2 VALUES (18, 'Department 18');

INSERT INTO dept_view2 VALUES (19, 'Department 20');

Page 26: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 26

Page 27: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Updating RowsUpdating Rows• The UPDATE statement updates existing rows through a The UPDATE statement updates existing rows through a

view. Here, a department name is changed from view. Here, a department name is changed from Department 20 to Department 19.Department 20 to Department 19.

/* SQL Example 8.24 */ UPDATE dept_view2 SET dpt_name = 'Department 19' WHERE dpt_no = 19; (1 row(s) affected)

/* SQL Example 8.25 */ SELECT * FROM department;

dpt_no dpt_name dpt_mgrssn dpt_mgr_start_date ––-––– ––––—–––––-–––––– –-–––––––– ––––––––––––––––––––––– 1 Headquarters 999666666 1981-06-19 00:00:00.000 3 Admin and Records 999555555 2001-01-01 00:00:00.000 7 Production 999444444 1998-05-22 00:00:00.000 18 Department 18 NULL NULL 19 Department 19 NULL NULL

Page 28: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Deleting RowsDeleting Rows

• This example deletes rows for departments 18 and 19.This example deletes rows for departments 18 and 19./* SQL Example 8.26 */DELETE dept_view2 WHERE dpt_no = 18 OR dpt_no = 19;(2 row(s) affected)

/* SQL Example 8.27 */SELECT *FROM department;

dpt_no dpt_name dpt_mgrssn dpt_mgr_start_date–––––– ––––––––––—–––––- –––––––—-- –––––-----------------–1 Headquarters 999666666 1981-06-19 00:00:00.0003 Admin and Records 999555555 2001-01-01 00:00:00.0007 Production 999444444 1998-05-22 00:00:00.000

Page 29: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

TABLES and the IDENTITY PROPERTYTABLES and the IDENTITY PROPERTY

• Suppose a furniture store needs to generate unique Suppose a furniture store needs to generate unique numbers to identify sales orders – how are these numbers to identify sales orders – how are these numbers produced?numbers produced?

• Solution – let the computer generate them from a Solution – let the computer generate them from a sequence of numbers.sequence of numbers.

• SQL Server provides this capability through tables SQL Server provides this capability through tables that have a column defined with the that have a column defined with the IdentityIdentity property clause.property clause.

• The general syntax of the IDENTITY clause is:IDENTITY [ ( initial_value , increment ) ]

Page 30: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

CREATE TABLE Syntax with CREATE TABLE Syntax with Identity ColumnIdentity Column

• The The sales_ordersales_order table example. table example.• The IDENTITY clause causes automatic generation The IDENTITY clause causes automatic generation

of of so_numberso_number column values with an initial value of column values with an initial value of 100 and increment of 1.100 and increment of 1.

/* SQL Example 8.28 */

CREATE TABLE sales_order (

so_number INTEGER IDENTITY(100,1)

CONSTRAINT pk_sales_order PRIMARY KEY,

so_value DECIMAL(9,2),

so_emp_ssn CHAR(9),

CONSTRAINT fk_so_emp_ssn

FOREIGN KEY (so_emp_ssn)

REFERENCES employee );

Page 31: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Inserting Sales_Order RowsInserting Sales_Order Rows

• The INSERT statement shown here inserts three The INSERT statement shown here inserts three rows into the rows into the sales_ordersales_order table. table.

• Notice that a value is not inserted for the Notice that a value is not inserted for the so_numberso_number column. column.

/* SQL Example 8.29 */INSERT INTO sales_order VALUES (155.59, '999111111');

INSERT INTO sales_order VALUES (450.00, '999444444');

INSERT INTO sales_order VALUES (16.95, '999444444');

Page 32: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Selecting Sales_Order RowsSelecting Sales_Order Rows

• SQL Example 8.30 shows the results of the SQL Example 8.30 shows the results of the three INSERT statements.three INSERT statements.

/* SQL Example 8.30 */SELECT *FROM sales_order;so_number so_value so_emp_ssn–––—––––––– ––––—–––-– ––––––––––100 155.59 999111111101 450.00 999444444102 16.95 999444444

Page 33: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

The Related Order_Details TableThe Related Order_Details Table

• The The sales_ordersales_order table is related in a one-to- table is related in a one-to-many fashion with the many fashion with the order_detailsorder_details table. table.

• The The order_detailsorder_details table has a table has a Composite Composite PRIMARY KEYPRIMARY KEY that includes the that includes the od_numberod_number and and od_rowod_row columns – columns – od_rowod_row is a way of numbering each item on an is a way of numbering each item on an order while order while od_number od_number is system generated is system generated and serves as a and serves as a FOREIGN KEYFOREIGN KEY link to the link to the sales_ordersales_order table. table.

Page 34: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

The Related Order_Details Table Cont.The Related Order_Details Table Cont.

/* SQL Example 8.31 */CREATE TABLE order_details ( od_number INTEGER, od_row INTEGER, od_product_desc VARCHAR(15), od_quantity_ordered INTEGER, od_product_price DECIMAL(9,2),CONSTRAINT pk_order_details PRIMARY KEY (od_number, od_row),CONSTRAINT fk_order_number FOREIGN KEY (od_number) REFERENCES sales_order );

Page 35: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Inserting Rows in Sales_Order and Inserting Rows in Sales_Order and Order_DetailsOrder_Details

• Assume the first two Assume the first two sales_ordersales_order rows have been rows have been deleted.deleted.

/* Insert a new sales_order row and two order_detail rows */

INSERT INTO sales_order VALUES(200.00, '999111111' );GOBEGIN DECLARE @so_number INTEGER SELECT @so_number = (SELECT SCOPE_IDENTITY() ) INSERT INTO order_details VALUES (@so_number, 1, 'End Table', 1, 100.00); INSERT INTO order_details VALUES (@so_number, 2, 'Table Lamp', 2, 50.00);END

Page 36: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Inserting Rows in Sales_Order and Inserting Rows in Sales_Order and Order_Details Contd.Order_Details Contd.

• SQL Example 8.32 defines a variable with a SQL Example 8.32 defines a variable with a DECLARE statement -- DECLARE statement -- @so_number@so_number..

• The The SCOPE_IDENTITYSCOPE_IDENTITY function, a pre-defined function, a pre-defined SQL Server function returns from the database SQL Server function returns from the database system tables the value of the last identity number system tables the value of the last identity number generated by the system generated by the system withinwithin the same the same procedure—here the value for the PRIMARY procedure—here the value for the PRIMARY KEY for the new KEY for the new sales_ordersales_order row. row.

• The variable value of The variable value of @so_number@so_number is inserted into is inserted into the the order_detailsorder_details rows in order to create the rows in order to create the necessary referential integrity link.necessary referential integrity link.

Page 37: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Results of the Row InsertionsResults of the Row Insertions/* SQL Example 8.33 */SELECT *FROM sales_order;

so_number so_value so_emp_ssn–––-––––––– ––––-–––-– ––––––––––103 200.00 999111111

/* SQL Example 8.34 */SELECT od_number "So Number", od_row "Row", od_product_desc "Description", CAST(od_quantity_ordered As CHAR(3)) "Qty", od_product_price "Price"FROM order_details;

So Number Row Description Qty Price–––—–––—––– –––-– ––—–––––––––– –––– ––––––103 1 End Table 1 100.00103 2 Table Lamp 2 50.00

Page 38: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

Reviewing the Row InsertionsReviewing the Row Insertions

• The The IdentityIdentity property of the property of the so_numberso_number column column of the of the sales_ordersales_order table automatically generated table automatically generated the next identity number (the next identity number (103103). ).

• The The SCOPE_IDENTITYSCOPE_IDENTITY function enabled function enabled accessing this value from database system tables accessing this value from database system tables in order to insert the value into the in order to insert the value into the od_numberod_number column of the column of the order_detailsorder_details table. table.

• The two tables are linked through these columns The two tables are linked through these columns and their common values.and their common values.

Page 39: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Bordoloi and BockBordoloi and Bock

SummarySummary• Views are an important mechanism to facilitate the Views are an important mechanism to facilitate the

display of selected table columns.display of selected table columns.• Views provide a form of database security by Views provide a form of database security by

limiting access to columns displayed.limiting access to columns displayed.• Views can be used for DML of underlying tables if Views can be used for DML of underlying tables if

they are “updateable” views.they are “updateable” views.• Identity columns can be used to generate primary Identity columns can be used to generate primary

key values automatically.key values automatically.• The SCOPE_IDENTITY property enables The SCOPE_IDENTITY property enables

retrieval of identity number values from database retrieval of identity number values from database system tables to enforce referential integrity system tables to enforce referential integrity between two or more tables.between two or more tables.

Page 40: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 40

Chapter 9: Additional FunctionsChapter 9: Additional Functions

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

Page 41: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 41

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 42: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 42

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 43: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 43

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 44: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 44

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 45: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 45

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 163http://www.lookuptables.com/

Page 46: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 46

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 argumentFLOAT data type with a decimal point as a required argument– Works with int also Works with int also

• 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 47: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 47

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 48: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 48

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 TEXT VARCHAR or NVARCHAR, but cannot be TEXT or NTEXT (too big < 2GB). or NTEXT (too big < 2GB).

• 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 49: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 49

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 50: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 50

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 51: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 51

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 52: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 52

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 53: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 53

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 54: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 54

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 55: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 55

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 56: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 56

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 57: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 57

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 58: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 58

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 59: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 59

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 60: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 60

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 61: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 61

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 62: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 62

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

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

• We will not focus on most of these as they are rarely We will not focus on most of these as they are rarely used in business except for the financial and 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 63: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 63

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 64: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 64

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 65: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 65

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 66: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 66

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 is SQUARE squares FLOAT numeric values – this is equivalent to POWER(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 67: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 67

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 68: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 68

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 69: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 69

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 70: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 70

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 71: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 71

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 (page 234).using the style parameter code of 107 (page 234).

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 72: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 72

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 73: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 73

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 74: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 74

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 75: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 75

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.

http://msdn.microsoft.com/en-us/library/ms174420.aspx

Page 76: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 76

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 77: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 77

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 78: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 78

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 79: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 79

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 80: Prentice Hall © 20041 COS 346 Day 15. 7-2 Agenda Questions?Questions? Assignment 6 Not correctedAssignment 6 Not corrected Assignment 7 PostedAssignment

Prentice Hall © 2004 80

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.