Implementing Views and BatchesObjectivesIn this lesson, you will learn to: Create, alter, drop, and rename views Update da...
Implementing Views and BatchesGetting Started Views     A view is a virtual table, which gives access to a subset      of ...
Implementing Views and BatchesGetting Started (Contd.)        ®   The statistical summary of data in a given table        ...
Implementing Views and Batches8.D.1 Creating Views You need to view skills of various employees. Some of the  queries to b...
Implementing Views and Batches8.D.1 Creating Views (Contd.)    JOIN Skill ON PositionSkill.cSkillCode =    Skill.cSkillCod...
Implementing Views and Batches8.D.1 Creating Views (Contd.)    SELECT vFirstName, vLastName,    vQualification, vSkill    ...
Implementing Views and BatchesTask List Identify how to simplify queries Draft the query for the view Create the view Veri...
Implementing Views and BatchesIdentify how to simplify queries Result:     Simplification of the query can be done using v...
Implementing Views and BatchesDraft the query for the view Action:     The tables from where the view derives its data are...
Implementing Views and BatchesCreate the view A view can be created using the CREATE VIEW statement Syntax  CREATE VIEW vi...
Implementing Views and BatchesCreate the view (Contd.) Action:     In the Query Analyzer window, type:      CREATE VIEW vw...
Implementing Views and BatchesVerify that the queries have been simplified byexecuting the required queries on the view Ac...
Implementing Views and BatchesVerify that the queries have been simplified byexecuting the required queries on the view (C...
Implementing Views and BatchesJust a Minute... Some queries to be executed are as follows:  SELECT vFirstName, vDepartment...
Implementing Views and BatchesJust a Minute (Contd.)SELECT vFirstName, vAddress, cCity, cZip,cDesignation, vDepartmentName...
Implementing Views and BatchesAltering, Dropping, and Renaming Views Altering Views     You can modify a view by using the...
Implementing Views and BatchesAltering, Dropping, and Renaming Views (Contd.) Dropping Views     You can drop a view from ...
Implementing Views and BatchesAltering, Dropping, and Renaming Views (Contd.) Renaming Views     A view can be renamed usi...
Implementing Views and Batches8.D.2 Modifying Data Using Views A view is defined as follows:   CREATE VIEW vwEmployeeCandi...
Implementing Views and Batches8.D.2 Modifying Data Using Views (Contd.)  While updating the test score and the telephone n...
Implementing Views and BatchesTask List Identify the error and a method to modify data Draft separate statements to update...
Implementing Views and BatchesIdentify the error and a method to modify data Modifying data through views     Data is pres...
Implementing Views and BatchesIdentify the error and a method to modify data (Contd.) Result:     You are unable to update...
Implementing Views and BatchesDraft separate statements to update tables Action:     The following statement would update ...
Implementing Views and BatchesUpdate tables Action:     In the Query Analyzer window, type:        UPDATE vwEmployeeCandid...
Implementing Views and BatchesVerify that the tables have been updated Action:     In the Query Analyzer window, type:    ...
Implementing Views and Batches8.P.1 Modifying Data Using Views A view was defined as follows:   CREATE VIEW vwNewspaperNew...
Implementing Views and BatchesProgramming for SQL Server There are several methods of programming SQL Server  applications...
Implementing Views and BatchesProgramming for SQL Server (Contd.) Batches     Batches are groups of SQL statements submitt...
Implementing Views and BatchesProgramming for SQL Server (Contd.) In Transact SQL, there are two kinds of variables, local...
Implementing Views and BatchesProgramming for SQL Server (Contd.) Printing Messages     The PRINT statement is used to dis...
Implementing Views and BatchesProgramming for SQL Server (Contd.) Comment Entry     A comment entry is used in batches to ...
Implementing Views and BatchesProgramming for SQL Server (Contd.) Control-of-Flow Language     The control-of-flow languag...
Implementing Views and BatchesJust a Minute... Fill in the blanks:    a. A group of SQL statements submitted together to S...
Implementing Views and Batches8.D.3 Using the IF Statement The minimum test score for an internal candidate to be  called ...
Implementing Views and BatchesTask List Identify how to display the required messages Draft the batch on paper Execute the...
Implementing Views and BatchesIdentify how to display the required messages The IF…ELSE Statement     This statement can b...
Implementing Views and BatchesIdentify how to display the required messages (Contd.) BEGIN…END Statement     If there are ...
Implementing Views and BatchesIdentify how to display the required messages (Contd.) Result:     The messages can be displ...
Implementing Views and BatchesDraft the batch on paper Result:     The batch statements are shown below.       DECLARE @iT...
Implementing Views and BatchesExecute the batch Action:     In the Query Analyzer window, type the statement given      be...
Implementing Views and BatchesExecute the batch (Contd.)        ELSE        BEGIN            PRINT Called for interview   ...
Implementing Views and BatchesVerify the batch Action:    Verify your answer by executing the following query:        SELE...
Implementing Views and BatchesMore Constructs The CASE Statement     In situations where several conditions need to be    ...
Implementing Views and BatchesMore Constructs (Contd.) The WHILE Statement     You can use the WHILE construct in a batch,...
Implementing Views and BatchesMore Constructs (Contd.) The BREAK and CONTINUE Statements     You can use the BREAK and CON...
Implementing Views and BatchesSummaryIn this lesson, you learned that: A view is a virtual table, which consists of a subs...
Implementing Views and BatchesSummary (Contd.) A view can be created with the CREATE VIEW statement SQL Server allows data...
Implementing Views and BatchesSummary (Contd.) You can use the PRINT statement to display a user-defined  message or the c...
Implementing Views and BatchesSummary (Contd.) The BREAK statement causes an exit from the WHILE loop The CONTINUE stateme...
Upcoming SlideShare
Loading in …5
×

Sql xp 08

691 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
691
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
34
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Sql xp 08

  1. 1. Implementing Views and BatchesObjectivesIn 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 SQL/Lesson 8/Slide 1 of 50©NIIT
  2. 2. Implementing Views and BatchesGetting 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 SQL/Lesson 8/Slide 2 of 50©NIIT
  3. 3. Implementing Views and BatchesGetting 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 SQL/Lesson 8/Slide 3 of 50©NIIT
  4. 4. Implementing Views and Batches8.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.cPos itionCode SQL/Lesson 8/Slide 4 of 50©NIIT
  5. 5. Implementing Views and Batches8.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 SQL/Lesson 8/Slide 5 of 50©NIIT
  6. 6. Implementing Views and Batches8.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. SQL/Lesson 8/Slide 6 of 50©NIIT
  7. 7. Implementing Views and BatchesTask 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 SQL/Lesson 8/Slide 7 of 50©NIIT
  8. 8. Implementing Views and BatchesIdentify how to simplify queries Result: Simplification of the query can be done using views SQL/Lesson 8/Slide 8 of 50©NIIT
  9. 9. Implementing Views and BatchesDraft 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 SQL/Lesson 8/Slide 9 of 50©NIIT
  10. 10. Implementing Views and BatchesCreate 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] SQL/Lesson 8/Slide 10 of 50©NIIT
  11. 11. Implementing Views and BatchesCreate the view (Contd.) Action: In the Query Analyzer window, type: CREATE VIEW vwEmpSkill AS SELECT vFirstName, vLastName, vQualification, vSkill FROM Employee JOIN PositionSkill ON Employee.cCurrentPosition = PositionSkill.cPositionCode JOIN Skill ON PositionSkill.cSkillCode = Skill.cSkillCode Press F5 to execute the command SQL/Lesson 8/Slide 11 of 50©NIIT
  12. 12. Implementing Views and BatchesVerify that the queries have been simplified byexecuting 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 SQL/Lesson 8/Slide 12 of 50©NIIT
  13. 13. Implementing Views and BatchesVerify that the queries have been simplified byexecuting 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 SQL/Lesson 8/Slide 13 of 50©NIIT
  14. 14. Implementing Views and BatchesJust 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 SQL/Lesson 8/Slide 14 of 50©NIIT
  15. 15. Implementing Views and BatchesJust a Minute (Contd.)SELECT vFirstName, vAddress, cCity, cZip,cDesignation, vDepartmentName, vDepartmentHeadFROM Employee JOIN DepartmentON Employee.cDepartmentCode =Department.cDepartmentCodeWHERE cCity = ColumbusSimplify the task of executing these queries. SQL/Lesson 8/Slide 15 of 50©NIIT
  16. 16. Implementing Views and BatchesAltering, 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] SQL/Lesson 8/Slide 16 of 50©NIIT
  17. 17. Implementing Views and BatchesAltering, 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 SQL/Lesson 8/Slide 17 of 50©NIIT
  18. 18. Implementing Views and BatchesAltering, 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 SQL/Lesson 8/Slide 18 of 50©NIIT
  19. 19. Implementing Views and Batches8.D.2 Modifying Data Using Views A view is defined as follows: CREATE VIEW vwEmployeeCandidate AS SELECT Employee.cCandidateCode, vFirstName, vLastName, cPhone, siTestScore FROM Employee JOIN InternalCandidate ON Employee.cCandidateCode=InternalCandidate. cCandidateCode SQL/Lesson 8/Slide 19 of 50©NIIT
  20. 20. Implementing Views and Batches8.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=75 WHERE cCandidateCode=‘000018’ Identify the error and correct it so that data in the tables is modified. SQL/Lesson 8/Slide 20 of 50©NIIT
  21. 21. Implementing Views and BatchesTask 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 SQL/Lesson 8/Slide 21 of 50©NIIT
  22. 22. Implementing Views and BatchesIdentify 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 SQL/Lesson 8/Slide 22 of 50©NIIT
  23. 23. Implementing Views and BatchesIdentify 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 SQL/Lesson 8/Slide 23 of 50©NIIT
  24. 24. Implementing Views and BatchesDraft 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-5634WHERE cCandidateCode = 000018 The following statement would update siTestScore attribute in the InternalCandidate table: UPDATE vwEmployeeCandidate SET siTestScore=75 WHERE cCandidateCode=000018 SQL/Lesson 8/Slide 24 of 50©NIIT
  25. 25. Implementing Views and BatchesUpdate 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 SQL/Lesson 8/Slide 25 of 50©NIIT
  26. 26. Implementing Views and BatchesVerify that the tables have been updated Action: In the Query Analyzer window, type: SELECT * FROM Employee WHERE cCandidateCode = 000018 SELECT * FROM InternalCandidate WHERE cCandidateCode = 000018 Press F5 key to execute the queries SQL/Lesson 8/Slide 26 of 50©NIIT
  27. 27. Implementing Views and Batches8.P.1 Modifying Data Using Views A view was defined as follows: CREATE VIEW vwNewspaperNewsad AS SELECT cNewspaperName,vCity,cZip,dAdStartDate FROM Newspaper JOIN NewsAd ON Newspaper.cNewspaperCode = NewsAd.cNewspaperCode The following statement, when given to update the table, did not update the table: UPDATE cNewspaperNewsAd SET cZip=88993-4532,dAdStartDate=01/09/99 WHERE cNewspaperName=Daily News Modify data in the base tables. SQL/Lesson 8/Slide 27 of 50©NIIT
  28. 28. Implementing Views and BatchesProgramming 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 SQL/Lesson 8/Slide 28 of 50©NIIT
  29. 29. Implementing Views and BatchesProgramming 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 SQL/Lesson 8/Slide 29 of 50 ©NIIT
  30. 30. Implementing Views and BatchesProgramming 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 SQL/Lesson 8/Slide 30 of 50©NIIT
  31. 31. Implementing Views and BatchesProgramming 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 SQL/Lesson 8/Slide 31 of 50©NIIT
  32. 32. Implementing Views and BatchesProgramming 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) SQL/Lesson 8/Slide 32 of 50©NIIT
  33. 33. Implementing Views and BatchesProgramming 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 SQL/Lesson 8/Slide 33 of 50©NIIT
  34. 34. Implementing Views and BatchesJust 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. SQL/Lesson 8/Slide 34 of 50©NIIT
  35. 35. Implementing Views and Batches8.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. SQL/Lesson 8/Slide 35 of 50©NIIT
  36. 36. Implementing Views and BatchesTask List Identify how to display the required messages Draft the batch on paper Execute the batch Verify the batch SQL/Lesson 8/Slide 36 of 50©NIIT
  37. 37. Implementing Views and BatchesIdentify 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}] SQL/Lesson 8/Slide 37 of 50©NIIT
  38. 38. Implementing Views and BatchesIdentify 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 Syntax BEGIN {sql_statement | statement_ block} END SQL/Lesson 8/Slide 38 of 50©NIIT
  39. 39. Implementing Views and BatchesIdentify how to display the required messages (Contd.) Result: The messages can be displayed using the PRINT and IF…ELSE statements in a batch SQL/Lesson 8/Slide 39 of 50©NIIT
  40. 40. Implementing Views and BatchesDraft the batch on paper Result: The batch statements are shown below. DECLARE @iTest int SELECT @iTest = siTestScore FROM InternalCandidate WHERE cEmployeeCode = 000008 IF @iTest 80 PRINT Rejected - Not called for interview ELSE BEGIN PRINT Called for interview PRINT your test score = PRINT @iTest END SQL/Lesson 8/Slide 40 of 50©NIIT
  41. 41. Implementing Views and BatchesExecute the batch Action: In the Query Analyzer window, type the statement given below. DECLARE @iTest int SELECT @iTest = siTestScore FROM InternalCandidate WHERE cEmployeeCode = 000008 IF @iTest 80 PRINT Rejected - Not called for interview SQL/Lesson 8/Slide 41 of 50©NIIT
  42. 42. Implementing Views and BatchesExecute the batch (Contd.) ELSE BEGIN PRINT Called for interview PRINT your test score = PRINT @iTest END Press F5 to execute the batch SQL/Lesson 8/Slide 42 of 50©NIIT
  43. 43. Implementing Views and BatchesVerify the batch Action: Verify your answer by executing the following query: SELECT siTestScore FROM InternalCandidate WHERE cEmployeeCode = 000008 SQL/Lesson 8/Slide 43 of 50©NIIT
  44. 44. Implementing Views and BatchesMore 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 SQL/Lesson 8/Slide 44 of 50©NIIT
  45. 45. Implementing Views and BatchesMore 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] SQL/Lesson 8/Slide 45 of 50©NIIT
  46. 46. Implementing Views and BatchesMore 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 SQL/Lesson 8/Slide 46 of 50©NIIT
  47. 47. Implementing Views and BatchesSummaryIn 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 SQL/Lesson 8/Slide 47 of 50©NIIT
  48. 48. Implementing Views and BatchesSummary (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 SQL/Lesson 8/Slide 48 of 50©NIIT
  49. 49. Implementing Views and BatchesSummary (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 SQL/Lesson 8/Slide 49 of 50©NIIT
  50. 50. Implementing Views and BatchesSummary (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 SQL/Lesson 8/Slide 50 of 50©NIIT

×