Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 6: Modifying Data in Tables. Inserting Data into Tables Deleting Data from Tables Updating Data in Tables Overview of Transactions.

Similar presentations


Presentation on theme: "Module 6: Modifying Data in Tables. Inserting Data into Tables Deleting Data from Tables Updating Data in Tables Overview of Transactions."— Presentation transcript:

1 Module 6: Modifying Data in Tables

2 Inserting Data into Tables Deleting Data from Tables Updating Data in Tables Overview of Transactions

3 Lesson 1: Inserting Data into Tables INSERT Fundamentals INSERT Statement Definitions INSERT Statement Examples Inserting Values into Identity Columns INSERT and the OUTPUT Clause

4 INSERT Fundamentals INSERT [INTO] table_or_view [(column_list)] data_values The INSERT statement adds one or more new rows to a table INSERT inserts data_values as one or more rows into the specified table_or_view column_list is a list of column names used to specify the columns for which data is supplied INSERT Syntax:

5 INSERT Statement Definitions INSERT INTO MyTable (PriKey, Description) SELECT ForeignKey, Description FROM SomeView INSERT INTO MyTable (PriKey, Description) SELECT ForeignKey, Description FROM SomeView CREATE PROCEDURE dbo.SomeProcedure INSERT dbo.SomeTable EXECUTE SomeProcedure CREATE PROCEDURE dbo.SomeProcedure INSERT dbo.SomeTable EXECUTE SomeProcedure INSERT TOP (#) INTO SomeTableA SELECT SomeColumnX, SomeColumnY FROM SomeTableB INSERT TOP (#) INTO SomeTableA SELECT SomeColumnX, SomeColumnY FROM SomeTableB INSERT using SELECT INSERT using EXECUTE INSERT using TOP

6 INSERT Statement Examples Using a Simple INSERT Statement INSERT INTO Production.UnitMeasure VALUES (N'F2', N'Square Feet', GETDATE()); INSERT INTO Production.UnitMeasure VALUES (N'F2', N'Square Feet', GETDATE()); INSERT INTO Production.UnitMeasure VALUES (N'F2', N'Square Feet', GETDATE()), (N'Y2', N'Square Yards', GETDATE()); INSERT INTO Production.UnitMeasure VALUES (N'F2', N'Square Feet', GETDATE()), (N'Y2', N'Square Yards', GETDATE()); Inserting Multiple Rows of Data

7 Inserting Values into Identity Columns CREATE TABLE dbo.T1 ( column_1 int IDENTITY, column_2 VARCHAR(30)); GO INSERT T1 VALUES ('Row #1'); INSERT T1 (column_2) VALUES ('Row #2'); GO SET IDENTITY_INSERT T1 ON; GO INSERT INTO T1 (column_1,column_2) VALUES (-99, 'Explicit identity value'); GO SELECT column_1, column_2 FROM T1; CREATE TABLE dbo.T1 ( column_1 int IDENTITY, column_2 VARCHAR(30)); GO INSERT T1 VALUES ('Row #1'); INSERT T1 (column_2) VALUES ('Row #2'); GO SET IDENTITY_INSERT T1 ON; GO INSERT INTO T1 (column_1,column_2) VALUES (-99, 'Explicit identity value'); GO SELECT column_1, column_2 FROM T1; column_list and VALUES must be used to insert values into an identity column, and the SET IDENTITY_INSERT option must be ON for the table

8 INSERT and the OUTPUT Clause Using OUTPUT in an INSERT statement returns information from each row affected by the INSERT statement INSERT SomeTable OUTPUT dml_select_list INTO (@table_variable | output_table) (column_list) INSERT SomeTable OUTPUT dml_select_list INTO (@table_variable | output_table) (column_list) DECLARE @MyTableVar table( ScrapReasonID smallint, Name varchar(50), ModifiedDate datetime); INSERT Production.ScrapReason OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate INTO @MyTableVar VALUES (N'Operator error', GETDATE()); DECLARE @MyTableVar table( ScrapReasonID smallint, Name varchar(50), ModifiedDate datetime); INSERT Production.ScrapReason OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate INTO @MyTableVar VALUES (N'Operator error', GETDATE()); Example Query: Syntax:

9 Demonstration: Inserting Data into Tables In this demonstration, you will see how to: Insert a Single Row into a Table Insert Multiple Rows into a Table Insert Values into Identity Columns Use the OUTPUT Clause with the INSERT Statement

10 Lesson 2: Deleting Data from Tables DELETE Fundamentals DELETE Statement Definitions Defining and Using the TRUNCATE Statement TRUNCATE versus DELETE DELETE and the OUTPUT Clause

11 DELETE Fundamentals DELETE table_or_view FROM table_sources WHERE search_condition DELETE table_or_view FROM table_sources WHERE search_condition The DELETE statement removes one or more rows in a table or view DELETE removes rows from the table_or_view parameter that meet the search condition table_sources can be used to specify additional tables or views that can be used by the WHERE clause DELETE Syntax:

12 DELETE Statement Definitions DELETE FROM SomeTable; DELETE FROM SomeTable WHERE SomeColumn IN (Subquery Definition); DELETE FROM SomeTable WHERE SomeColumn IN (Subquery Definition); DELETE TOP (#) PERCENT FROM SomeTable; DELETE TOP (#) PERCENT FROM SomeTable; DELETE with no WHERE clause DELETE using a Subquery DELETE using TOP DELETE FROM Sales.SalesPerson; DELETE FROM Sales.SalesPersonQuotaHistory WHERE SalesPersonID IN (SELECT SalesPersonID FROM Sales.SalesPerson WHERE SalesYTD > 2500000.00); DELETE FROM Sales.SalesPersonQuotaHistory WHERE SalesPersonID IN (SELECT SalesPersonID FROM Sales.SalesPerson WHERE SalesYTD > 2500000.00); DELETE TOP (2.5) PERCENT FROM Production.ProductInventory; DELETE TOP (2.5) PERCENT FROM Production.ProductInventory;

13 Defining and Using the TRUNCATE Statement TRUNCATE TABLE HumanResources.JobCandidate; TRUNCATE TABLE [ { database_name.[ schema_name ]. | schema_name. } ] table_name [ ; ] TRUNCATE TABLE [ { database_name.[ schema_name ]. | schema_name. } ] table_name [ ; ] You cannot use TRUNCATE TABLE on tables that are referenced by a FOREIGN KEY constraint TRUNCATE TABLE Syntax TRUNCATE TABLE Example

14 TRUNCATE versus DELETE Fewer locks are typically used Zero pages are left in the table Less transaction log space is used TRUNCATE TABLE has the following advantages over DELETE: DELETE FROM Sales.SalesPerson; TRUNCATE TABLE Sales.SalesPerson;

15 DELETE and the OUTPUT Clause Using OUTPUT in a DELETE statement removes a row from a table and returns the deleted values to a result set DELETE SomeTable OUTPUT column_list DELETE SomeTable OUTPUT column_list DELETE Production.Culture OUTPUT DELETED.*; DELETE Production.Culture OUTPUT DELETED.*; Example Query: Syntax: CultureIDNameModifiedDate --------------------------------------- ArArabic1998-06-01 EnEnglish1998-06-01 CultureIDNameModifiedDate --------------------------------------- ArArabic1998-06-01 EnEnglish1998-06-01

16 Demonstration: Deleting Data from Tables In this demonstration, you will see how to: Delete Rows from a Table Truncate a Table Delete Rows Based on Other Tables Use the OUTPUT Clause with the DELETE Statement

17 Lesson 3: Updating Data in Tables UPDATE Fundamentals UPDATE Statement Definitions Updating with Information from another Table UPDATE and the OUTPUT Clause

18 UPDATE Fundamentals UPDATE table_or_view SET column_name = expression FROM table_sources WHERE search_condition UPDATE table_or_view SET column_name = expression FROM table_sources WHERE search_condition The UPDATE statement changes data values in one, many, or all rows of a table An UPDATE statement referencing a table or view can change the data in only one base table at a time UPDATE has three major clauses: SET – comma-separated list of columns to be updated FROM – supplies values for the SET clause WHERE – specifies a search condition for the SET clause UPDATE Syntax:

19 UPDATE Statement Definitions UPDATE SomeTable SET Column = Value UPDATE SomeTable SET Column = Value UPDATE SomeTable SET Column = Value WHERE SearchExpression UPDATE SomeTable SET Column = Value WHERE SearchExpression Simple UPDATE Statement UPDATE with a WHERE clause UPDATE Sales.SalesPerson SET Bonus = 6000; UPDATE Sales.SalesPerson SET Bonus = 6000; UPDATE Production.Product SET Color = N’Metallic Red’ WHERE Name LIKE N’Road-250%’ AND Color = N’Red’; UPDATE Production.Product SET Color = N’Metallic Red’ WHERE Name LIKE N’Road-250%’ AND Color = N’Red’; UPDATE Sales.SalesPerson SET Bonus = Bonus * 2; UPDATE Sales.SalesPerson SET Bonus = Bonus * 2;

20 Updating with Information from Another Table UPDATE SomeTable SET Column = Value FROM SomeSubquery UPDATE SomeTable SET Column = Value FROM SomeSubquery UPDATE using a Subquery UPDATE Sales.SalesPerson SET SalesYTD = SalesYTD + SubTotal FROM Sales.SalesPerson AS sp JOIN Sales.SalesOrderHeader AS so ON sp.BusinessEntityID = so.SalesPersonID AND so.OrderDate = (SELECT MAX(OrderDate) FROM Sales.SalesOrderHeader WHERE SalesPersonID = sp.BusinessEntityID); UPDATE Sales.SalesPerson SET SalesYTD = SalesYTD + SubTotal FROM Sales.SalesPerson AS sp JOIN Sales.SalesOrderHeader AS so ON sp.BusinessEntityID = so.SalesPersonID AND so.OrderDate = (SELECT MAX(OrderDate) FROM Sales.SalesOrderHeader WHERE SalesPersonID = sp.BusinessEntityID); SalesYTD -------------- 677558.4653 4557045.0459 SalesYTD -------------- 677558.4653 4557045.0459 Before SalesYTD -------------- 721382.488 4593234.5123 SalesYTD -------------- 721382.488 4593234.5123 After

21 UPDATE and the OUTPUT Clause Using OUTPUT in an UPDATE statement returns information from each row affected by the UPDATE statement UPDATE SomeTable OUTPUT dml_select_list FROM table_source WHERE search_condition UPDATE SomeTable OUTPUT dml_select_list FROM table_source WHERE search_condition DECLARE @NewTableVar table ( Dollars money ); UPDATE Sales.SalesPerson SET Bonus = 10000 OUTPUT INSERTED.Bonus INTO @NewTableVar; SELECT Dollars FROM @NewTableVar; DECLARE @NewTableVar table ( Dollars money ); UPDATE Sales.SalesPerson SET Bonus = 10000 OUTPUT INSERTED.Bonus INTO @NewTableVar; SELECT Dollars FROM @NewTableVar; Syntax: Dollars -------- 10000.00... (17 row(s) affected) Dollars -------- 10000.00... (17 row(s) affected)

22 Demonstration: Updating Data in Tables In this demonstration, you will see how to: Update Rows in a Table Update Rows Based on Other Tables Use the OUTPUT Clause with the UPDATE Statement

23 Lesson 4: Overview of Transactions Transaction Fundamentals Transactions and the Database Engine Basic Transaction Statement Definitions What are Transaction Isolation Levels? Using Nested Transactions

24 Transaction Fundamentals A Transaction: Is a sequence of operations performed as a single logical unit of work Exhibits the four ACID Properties Atomicity – must be an atomic unit of work Consistency - must leave all data in a consistent state Isolation - must be isolated from the modifications made by any other concurrent transactions Durability – persists even after system failure

25 Transactions and the Database Engine The Database Engine provides: Locking facilities that preserve transaction isolation Transaction Isolation Levels control when locks are taken and how long they are held Logging facilities that ensure transaction durability Write-ahead log (WAL) guarantees no data modifications are written before they are logged Checkpoints write records to a data file and contain lists of all active transactions Transaction management features that enforce transaction atomicity and consistency Transactions must be successfully completed or their modifications are undone

26 Basic Transaction Statement Definitions BEGIN { TRAN | TRANSACTION } [ Transaction_name | @tran_name_variable ] BEGIN { TRAN | TRANSACTION } [ Transaction_name | @tran_name_variable ] COMMIT { TRAN | TRANSACTION } [ transaction_name | @tran_name_variable ] BEGIN TRANSACTION COMMIT TRANSACTION BEGIN TRAN T1; UPDATE table1...; BEGIN TRAN T1; UPDATE table1...; COMMIT TRAN T1; ROLLBACK { TRAN | TRANSACTION } [ transaction_name | @tran_name_variable | savepoint_name | @savepoint_variable ] ROLLBACK TRANSACTION ROLLBACK TRAN T1;

27 Demonstration: Creating a Transaction In this demonstration, you will see how to: Create and Commit a New Transaction

28 What are Transaction Isolation Levels? Transaction Isolation Levels control Whether locks are taken when data is read How long read locks are held How a read operation referencing rows acts Choosing a transaction isolation level does not affect the locks acquired to protect data modifications SET TRANSACTION ISOLATION LEVEL ; Syntax The levels are READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SNAPSHOT, and SERIALIZABLE

29 Demonstration: Setting Transaction Isolation Levels In this demonstration, you will see how to: Set a Transaction Isolation Level

30 CREATE TABLE TestTrans(Cola INT PRIMARY KEY, Colb CHAR(3) NOT NULL); GO CREATE PROCEDURE TransProc @PriKey INT, @CharCol CHAR(3) AS BEGIN TRANSACTION InProc INSERT INTO TestTrans VALUES (@PriKey, @CharCol) INSERT INTO TestTrans VALUES (@PriKey + 1, @CharCol) COMMIT TRANSACTION InProc; GO BEGIN TRANSACTION OutOfProc; /* Starts a transaction */ GO EXEC TransProc 1, 'aaa'; GO ROLLBACK TRANSACTION OutOfProc; /* Rolls back the outer transaction */ GO EXECUTE TransProc 3,'bbb'; GO SELECT * FROM TestTrans; GO CREATE TABLE TestTrans(Cola INT PRIMARY KEY, Colb CHAR(3) NOT NULL); GO CREATE PROCEDURE TransProc @PriKey INT, @CharCol CHAR(3) AS BEGIN TRANSACTION InProc INSERT INTO TestTrans VALUES (@PriKey, @CharCol) INSERT INTO TestTrans VALUES (@PriKey + 1, @CharCol) COMMIT TRANSACTION InProc; GO BEGIN TRANSACTION OutOfProc; /* Starts a transaction */ GO EXEC TransProc 1, 'aaa'; GO ROLLBACK TRANSACTION OutOfProc; /* Rolls back the outer transaction */ GO EXECUTE TransProc 3,'bbb'; GO SELECT * FROM TestTrans; GO Using Nested Transactions Explicit transactions can be nested to support transactions in stored procedures ColaColb ------------ 1bb 2bb ColaColb ------------ 1bb 2bb

31 Demonstration: Using Nested Transactions In this demonstration, you will see how to: Create a Nested Transaction

32 Lab: Modifying Data Exercise 1: Inserting Data into Tables Exercise 2: Deleting Data from Tables Exercise 3: Updating Data in Tables Exercise 4: Working with Transactions Logon information Virtual machineNY-SQL-01 User nameAdministrator Password Pa$$w0rd Estimated time: 60 minutes

33 Lab Scenario You are a database developer at Adventure Works. You have been asked by the senior database administrator to add, delete, and change rows on several tables in the AdventureWorks2008 database. You must be sure to follow the specifications that the senior database administrator has provided you closely so you do not insert incorrect data into the tables, change data unnecessarily, or delete vital company data.

34 Lab Review Why are values for column names listed in the same order as columns on the table when using the INSERT statement? How can we verify that rows have been deleted after using the DELETE statement? How can we write an UPDATE statement to ensure that all rows of a table are affected?

35 Module Review and Takeaways Review Questions Best Practices

36 Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane.


Download ppt "Module 6: Modifying Data in Tables. Inserting Data into Tables Deleting Data from Tables Updating Data in Tables Overview of Transactions."

Similar presentations


Ads by Google