sql xp 08

50
©NIIT SQL/Lesson 8/Slide 1 of 50 Implementing Views and Batches Objectives In this lesson, you will learn to: Create, alter, drop, and rename views Update data using views Declare variables Print messages Use comments Use conditional statements Use the iteration statements

Upload: niit-care

Post on 22-May-2015

414 views

Category:

Technology


4 download

TRANSCRIPT

Page 1: Sql xp 08

©NIITSQL/Lesson 8/Slide 1 of 50

Implementing Views and Batches

Objectives

In this lesson, you will learn to:

Create, alter, drop, and rename views

Update data using views

Declare variables

Print messages

Use comments

Use conditional statements

Use the iteration statements

Page 2: Sql xp 08

©NIITSQL/Lesson 8/Slide 2 of 50

Implementing Views and Batches

Getting Started

Views

A view is a virtual table, which gives access to a subset of columns from one or more tables

Views ensure security of data by restricting access to:

Specific rows of a table

Specific columns of a table

Specific rows and columns of a table

The rows fetched using joins

Page 3: Sql xp 08

©NIITSQL/Lesson 8/Slide 3 of 50

Implementing Views and Batches

Getting Started (Contd.) The statistical summary of data in a given table

Subsets of another view or a subset of views and tables

Views provide several advantages:

Providing relevant data for users

Hiding data complexity

Organize data from heterogeneous sources

Reducing the object size

Page 4: Sql xp 08

©NIITSQL/Lesson 8/Slide 4 of 50

Implementing Views and Batches

8.D.1 Creating Views You need to view skills of various employees. Some of the

queries to be executed are as follows:

SELECT vFirstName, vSkill FROM Employee JOIN PositionSkill ON Employee.cCurrentPosition = PositionSkill.cPositionCode JOIN Skill ON PositionSkill.cSkillCode = Skill.cSkillCode

SELECT vFirstName, vLastName,vSkill FROM Employee JOIN PositionSkill ON Employee.cCurrentPosition=PositionSkill.cPositionCode

Page 5: Sql xp 08

©NIITSQL/Lesson 8/Slide 5 of 50

Implementing Views and Batches

8.D.1 Creating Views (Contd.)

JOIN Skill ON PositionSkill.cSkillCode = Skill.cSkillCode

SELECT vFirstName, vLastName, vSkill FROM Employee JOIN PositionSkill

ON Employee.cCurrentPosition =PositionSkill.cPositionCode

JOIN Skill ON PositionSkill.cSkillCode =Skill.cSkillCode

AND vFirstName = 'Angela'

Page 6: Sql xp 08

©NIITSQL/Lesson 8/Slide 6 of 50

Implementing Views and Batches

8.D.1 Creating Views (Contd.)

SELECT vFirstName, vLastName,

vQualification, vSkill

FROM Employee JOIN PositionSkill

ON Employee.cCurrentPosition = PositionSkill.cPositionCode JOIN Skill

ON PositionSkill.cSkillCode = Skill.cSkillCode

Simplify the task of executing these queries.

Page 7: Sql xp 08

©NIITSQL/Lesson 8/Slide 7 of 50

Implementing Views and Batches

Task List

Identify how to simplify queries

Draft the query for the view

Create the view

Verify that the queries have been simplified by executing the required queries on the view

Page 8: Sql xp 08

©NIITSQL/Lesson 8/Slide 8 of 50

Implementing Views and Batches

Identify how to simplify queries Result:

Simplification of the query can be done using views

Page 9: Sql xp 08

©NIITSQL/Lesson 8/Slide 9 of 50

Implementing Views and Batches

Draft the query for the view

Action:

The tables from where the view derives its data are Employee, positionSkill, and Skill

The columns that are to be included in the view are vFirstName, vLastName, and vQualification from the Employee table and vSkill from the Skill table

Page 10: Sql xp 08

©NIITSQL/Lesson 8/Slide 10 of 50

Implementing Views and Batches

Create the view

A view can be created using the CREATE VIEW statement

Syntax

CREATE VIEW view_name[(column_name [, column_name]...)][WITH ENCRYPTION]AS select_statement [WITH CHECK OPTION]

Page 11: Sql xp 08

©NIITSQL/Lesson 8/Slide 11 of 50

Implementing Views and Batches

Create the view (Contd.)

Action:

In the Query Analyzer window, type:CREATE VIEW vwEmpSkillASSELECT vFirstName, vLastName, vQualification, vSkill

FROM Employee JOIN PositionSkillON Employee.cCurrentPosition = PositionSkill.cPositionCode

JOIN SkillON PositionSkill.cSkillCode = Skill.cSkillCode

Press F5 to execute the command

Page 12: Sql xp 08

©NIITSQL/Lesson 8/Slide 12 of 50

Implementing Views and Batches

Verify that the queries have been simplified by executing the required queries on the view

Action:

In the Query Analyzer window, type:

SELECT vFirstName, vSkill FROM vwEmpSkill

Press F5 to execute the query

In the Query Analyzer window, type:

SELECT vFirstName, vLastName, vSkill

FROM vwEmpSkill

Press F5 to execute the query

Page 13: Sql xp 08

©NIITSQL/Lesson 8/Slide 13 of 50

Implementing Views and Batches

Verify that the queries have been simplified by executing the required queries on the view (Contd.)

In the Query Analyzer window, type:

SELECT vFirstName,vLastName,vSkill

FROM vwEmpSkill WHERE vFirstName = 'Angela'

Press F5 to execute the query

In the Query Analyzer window, type:

SELECT * FROM vwEmpSkill

Press F5 to execute the query

Page 14: Sql xp 08

©NIITSQL/Lesson 8/Slide 14 of 50

Implementing Views and Batches

Just a Minute...

Some queries to be executed are as follows:

SELECT vFirstName, vDepartmentName

FROM Employee JOIN Department

ON Employee.cDepartmentCode = Department.cDepartmentCode

SELECT vFirstName, cDesignation, vDepartmentName

FROM Employee JOIN Department

ON Employee.cDepartmentCode = Department.cDepartmentCode

Page 15: Sql xp 08

©NIITSQL/Lesson 8/Slide 15 of 50

Implementing Views and Batches

Just a Minute (Contd.)

SELECT vFirstName, vAddress, cCity, cZip, cDesignation, vDepartmentName, vDepartmentHead

FROM Employee JOIN Department

ON Employee.cDepartmentCode = Department.cDepartmentCode

WHERE cCity = 'Columbus'

Simplify the task of executing these queries.

Page 16: Sql xp 08

©NIITSQL/Lesson 8/Slide 16 of 50

Implementing Views and Batches

Altering, Dropping, and Renaming Views

Altering Views

You can modify a view by using the ALTER VIEW statement

Syntax

ALTER VIEW view_name [(column_name)]

[WITH ENCRYPTION]

AS select_statement

[WITH CHECK OPTION]

Page 17: Sql xp 08

©NIITSQL/Lesson 8/Slide 17 of 50

Implementing Views and Batches

Altering, Dropping, and Renaming Views (Contd.)

Dropping Views

You can drop a view from a database by using the DROP VIEW statement

Syntax

DROP VIEW view_name

Page 18: Sql xp 08

©NIITSQL/Lesson 8/Slide 18 of 50

Implementing Views and Batches

Altering, Dropping, and Renaming Views (Contd.)

Renaming Views

A view can be renamed using the sp_rename system stored procedure

Syntax

sp_rename old_viewname, new_viewname

Page 19: Sql xp 08

©NIITSQL/Lesson 8/Slide 19 of 50

Implementing Views and Batches

8.D.2 Modifying Data Using Views

A view is defined as follows:CREATE VIEW vwEmployeeCandidateASSELECT Employee.cCandidateCode, vFirstName, vLastName, cPhone, siTestScoreFROM Employee JOIN InternalCandidateON Employee.cCandidateCode=InternalCandidate. cCandidateCode

Page 20: Sql xp 08

©NIITSQL/Lesson 8/Slide 20 of 50

Implementing Views and Batches

8.D.2 Modifying Data Using Views (Contd.)

While updating the test score and the telephone number of an employee, whose candidate code is ‘000018’, the following command gives an error:UPDATE vwEmployeeCandidate SET cPhone = '(614)324-5634', siTestScore=75WHERE cCandidateCode=‘000018’

Identify the error and correct it so that data in the tables is modified.

Page 21: Sql xp 08

©NIITSQL/Lesson 8/Slide 21 of 50

Implementing Views and Batches

Task List

Identify the error and a method to modify data

Draft separate statements to update tables

Update tables

Verify that the tables have been updated

Page 22: Sql xp 08

©NIITSQL/Lesson 8/Slide 22 of 50

Implementing Views and Batches

Identify the error and a method to modify data

Modifying data through views

Data is present in the base tables, which can be modified by modifying data in the view

There are certain restrictions at the time of inserting, updating, or deleting data through views. These are:

You cannot modify data in a view if the modification affects more than one underlying table

You cannot change a column that is the result of a calculation

Page 23: Sql xp 08

©NIITSQL/Lesson 8/Slide 23 of 50

Implementing Views and Batches

Identify the error and a method to modify data (Contd.)

Result:

You are unable to update the attributes because views allow only one of the underlying tables to be updated at a time. You need to update the attributes by giving two separate UPDATE commands

Page 24: Sql xp 08

©NIITSQL/Lesson 8/Slide 24 of 50

Implementing Views and Batches

Draft separate statements to update tables

Action:

The following statement would update the cPhone attribute in the Employee base table:

UPDATE vwEmployeeCandidate SET cPhone = '(614)324-5634'WHERE cCandidateCode = '000018'

The following statement would update siTestScore attribute in the InternalCandidate table:UPDATE vwEmployeeCandidate

SET siTestScore=75 WHERE cCandidateCode='000018'

Page 25: Sql xp 08

©NIITSQL/Lesson 8/Slide 25 of 50

Implementing Views and Batches

Update tables

Action:

In the Query Analyzer window, type:

UPDATE vwEmployeeCandidate SET cPhone = '(614)324-5634' WHERE cCandidateCode = '000018'

UPDATE vwEmployeeCandidate

SET siTestScore = 75 WHERE cCandidateCode = '000018'

Press F5 to execute the statement

Page 26: Sql xp 08

©NIITSQL/Lesson 8/Slide 26 of 50

Implementing Views and Batches

Verify that the tables have been updated

Action:

In the Query Analyzer window, type:SELECT * FROM Employee WHERE cCandidateCode = '000018'

SELECT * FROM InternalCandidateWHERE cCandidateCode = '000018'

Press F5 key to execute the queries

Page 27: Sql xp 08

©NIITSQL/Lesson 8/Slide 27 of 50

Implementing Views and Batches

8.P.1 Modifying Data Using Views

A view was defined as follows:CREATE VIEW vwNewspaperNewsadASSELECT cNewspaperName,vCity,cZip,dAdStartDateFROM Newspaper JOIN NewsAdON Newspaper.cNewspaperCode =NewsAd.cNewspaperCode

The following statement, when given to update the table, did not update the table:UPDATE cNewspaperNewsAdSET cZip='88993-4532',dAdStartDate='01/09/99'WHERE cNewspaperName='Daily News'

Modify data in the base tables.

Page 28: Sql xp 08

©NIITSQL/Lesson 8/Slide 28 of 50

Implementing Views and Batches

Programming for SQL Server

There are several methods of programming SQL Server applications. The following sections describe the different approaches that you can use for programming in terms of:

Batches

Variables

Printing Messages

Comments

Control-of-flow statements

Page 29: Sql xp 08

©NIITSQL/Lesson 8/Slide 29 of 50

Implementing Views and Batches

Programming for SQL Server (Contd.)

Batches

Batches are groups of SQL statements submitted together to SQL Server for execution

SQL server processes a batch interactively or from a file

Variables

You can use a variable to store a temporary value

Syntax

DECLARE @variable_name data_type

Example

DECLARE @Charge int

Page 30: Sql xp 08

©NIITSQL/Lesson 8/Slide 30 of 50

Implementing Views and Batches

Programming for SQL Server (Contd.)

In Transact SQL, there are two kinds of variables, local and global

The variable @Charge is declared within a batch and is lost when the execution of the batch is over. Such variables are called local variables and, since we defined them, they are called the user-defined variables

Global variables are those that are declared by the server and typically assigned values by the server

Page 31: Sql xp 08

©NIITSQL/Lesson 8/Slide 31 of 50

Implementing Views and Batches

Programming for SQL Server (Contd.)

Printing Messages

The PRINT statement is used to display a user-defined message or the content of a variable on the screen

Example

DECLARE @MyName char (50)

SELECT @MyName = 'Coomar Chris'

PRINT @MyName

Page 32: Sql xp 08

©NIITSQL/Lesson 8/Slide 32 of 50

Implementing Views and Batches

Programming for SQL Server (Contd.) Comment Entry

A comment entry is used in batches to write a description of the code

It can be written in two ways: Multiple line comment entries enclosed within /* and */ Single line comment entry starting with a -- (double

hyphens)

Page 33: Sql xp 08

©NIITSQL/Lesson 8/Slide 33 of 50

Implementing Views and Batches

Programming for SQL Server (Contd.)

Control-of-Flow Language

The control-of-flow language controls the flow of execution of SQL statements in batches, stored procedures, triggers and transactions

The control-of-flow statements provided by SQL Server for programming are:

The IF…ELSE statement

The CASE statement

The WHILE statement

Page 34: Sql xp 08

©NIITSQL/Lesson 8/Slide 34 of 50

Implementing Views and Batches

Just a Minute...

Fill in the blanks:

a. A group of SQL statements submitted together to SQL server for execution is called a ________.

b. _________ declared within a batch and is lost when the execution of the batch is over.

Page 35: Sql xp 08

©NIITSQL/Lesson 8/Slide 35 of 50

Implementing Views and Batches

8.D.3 Using the IF Statement

The minimum test score for an internal candidate to be called for an interview is 80. Write a batch that would display “Called for interview” along with the test score, if the test score is more than 80, and display “Rejected - Not called for interview” if it is less than 80, for an employee whose employee code is 000008.

Page 36: Sql xp 08

©NIITSQL/Lesson 8/Slide 36 of 50

Implementing Views and Batches

Task List

Identify how to display the required messages

Draft the batch on paper

Execute the batch

Verify the batch

Page 37: Sql xp 08

©NIITSQL/Lesson 8/Slide 37 of 50

Implementing Views and Batches

Identify how to display the required messages

The IF…ELSE Statement

This statement can be used for conditional execution of SQL statements

Syntax

IF boolean_expression {sql_statement | statement_block}[ELSE boolean_expression {sql_statement | statement_block}]

Page 38: Sql xp 08

©NIITSQL/Lesson 8/Slide 38 of 50

Implementing Views and Batches

Identify how to display the required messages (Contd.)

BEGIN…END Statement

If there are multiple T-SQL statements, then these must be enclosed within the BEGIN and END keywords

SyntaxBEGIN

{sql_statement | statement_ block}END

Page 39: Sql xp 08

©NIITSQL/Lesson 8/Slide 39 of 50

Implementing Views and Batches

Identify how to display the required messages (Contd.)

Result:

The messages can be displayed using the PRINT and IF…ELSE statements in a batch

Page 40: Sql xp 08

©NIITSQL/Lesson 8/Slide 40 of 50

Implementing Views and Batches

Draft the batch on paper

Result:

The batch statements are shown below.DECLARE @iTest intSELECT @iTest = siTestScore FROM InternalCandidateWHERE cEmployeeCode = '000008'IF @iTest < 80PRINT 'Rejected - Not called for interview'ELSEBEGIN PRINT 'Called for interview' PRINT 'your test score =' PRINT @iTestEND

Page 41: Sql xp 08

©NIITSQL/Lesson 8/Slide 41 of 50

Implementing Views and Batches

Execute the batch

Action:

In the Query Analyzer window, type the statement given below.DECLARE @iTest intSELECT @iTest = siTestScore FROM InternalCandidateWHERE cEmployeeCode = '000008'IF @iTest < 80 PRINT 'Rejected - Not called for interview'

Page 42: Sql xp 08

©NIITSQL/Lesson 8/Slide 42 of 50

Implementing Views and Batches

Execute the batch (Contd.)

ELSEBEGIN PRINT 'Called for interview' PRINT 'your test score =' PRINT @iTestEND

Press F5 to execute the batch

Page 43: Sql xp 08

©NIITSQL/Lesson 8/Slide 43 of 50

Implementing Views and Batches

Verify the batch

Action: Verify your answer by executing the following query:

SELECT siTestScoreFROM InternalCandidate WHERE cEmployeeCode = '000008'

Page 44: Sql xp 08

©NIITSQL/Lesson 8/Slide 44 of 50

Implementing Views and Batches

More Constructs

The CASE Statement

In situations where several conditions need to be evaluated, SQL Server provides a programming construct called the CASE statement

Syntax

CASE WHEN boolean_expression THEN

expression[[WHEN boolean_expression THEN

expression] [...]][ELSE expression]

END

Page 45: Sql xp 08

©NIITSQL/Lesson 8/Slide 45 of 50

Implementing Views and Batches

More Constructs (Contd.)

The WHILE Statement

You can use the WHILE construct in a batch, a stored procedure, a trigger, or a cursor to allow a set of T-SQL statements to execute repeatedly as long as the given condition holds true

Syntax

WHILE boolean_expression {sql_statement | statement_block}[BREAK]{sql_statement | statement_block}[CONTINUE]

Page 46: Sql xp 08

©NIITSQL/Lesson 8/Slide 46 of 50

Implementing Views and Batches

More Constructs (Contd.)

The BREAK and CONTINUE Statements

You can use the BREAK and CONTINUE statements to control the execution of the statements inside a WHILE loop

The BREAK statement causes an exit from the WHILE loop

The CONTINUE statement causes the WHILE loop to restart, skipping any statements after CONTINUE inside the loop

Page 47: Sql xp 08

©NIITSQL/Lesson 8/Slide 47 of 50

Implementing Views and Batches

Summary

In this lesson, you learned that:

A view is a virtual table, which consists of a subset of columns from one or more tables

A view derives its data from one or more tables known as base or underlying tables

Views serve as security mechanisms, thereby protecting data in the base tables

A view can restrict access to data in specific columns, specific rows, specific rows and columns, rows fetched by using joins, statistical summary of data in a given table, subsets of another view or a subset of views and tables

Page 48: Sql xp 08

©NIITSQL/Lesson 8/Slide 48 of 50

Implementing Views and Batches

Summary (Contd.)

A view can be created with the CREATE VIEW statement

SQL Server allows data to be modified only in one of the underlying tables when using views, even if the view is derived from multiple underlying tables

A view can be modified with the ALTER VIEW statement

A view can be dropped with the DROP VIEW statement

A view can be renamed with the sp_rename stored procedure

A batch is a set of SQL statements submitted together to the server for execution

You can use a variable to store a temporary value

Page 49: Sql xp 08

©NIITSQL/Lesson 8/Slide 49 of 50

Implementing Views and Batches

Summary (Contd.)

You can use the PRINT statement to display a user-defined message or the content of a variable on the screen

You can use the comment entries in batches to write a description of the code

You can use the IF…ELSE statement for conditional execution of SQL statements

The CASE statement evaluates a list of conditions and returns one of the various possible results

You can use the WHILE statement in a batch to allow a set of T-SQL statements to execute repeatedly as long as the given condition holds true

Page 50: Sql xp 08

©NIITSQL/Lesson 8/Slide 50 of 50

Implementing Views and Batches

Summary (Contd.) The BREAK statement causes an exit from the WHILE loop

The CONTINUE statement causes the WHILE loop to restart, skipping any statements after CONTINUE inside the loop