2778A_06

download 2778A_06

of 35

Transcript of 2778A_06

  • 7/31/2019 2778A_06

    1/35

    Module 6:

    Modifying Data in Tables

  • 7/31/2019 2778A_06

    2/35

    Module 6: Modifying Data in Tables

    Inserting Data into Tables

    Deleting Data from Tables

    Updating Data in Tables

    Overview of Transactions

  • 7/31/2019 2778A_06

    3/35

    Lesson 1: Inserting Data into Tables

    INSERT Fundamentals

    INSERT Statement Definitions

    INSERT Statement Examples

    Inserting Values into Identity Columns

    INSERT and the OUTPUT Clause

  • 7/31/2019 2778A_06

    4/35

    INSERT Fundamentals

    INSERT [INTO] table_or_view [(column_list)] data_values

    The INSERT statement adds one or more new rows toa table

    INSERT inserts data_values as one or more rows intothe specified table_or_view

    column_listis a list of column names used to specifythe columns for which data is supplied

    INSERT Syntax:

  • 7/31/2019 2778A_06

    5/35

    INSERT Statement Definitions

    INSERT INTO MyTable (PriKey, Description)SELECT ForeignKey, DescriptionFROM SomeView

    CREATE PROCEDURE dbo.SomeProcedureINSERT dbo.SomeTableEXECUTE SomeProcedure

    INSERT TOP (#) INTO SomeTableASELECT SomeColumnX, SomeColumnYFROM SomeTableB

    INSERT using SELECT

    INSERT using EXECUTE

    INSERT using TOP

  • 7/31/2019 2778A_06

    6/35

    INSERT Statement Examples

    Using a Simple INSERT Statement

    INSERT INTO Production.UnitMeasureVALUES (N'F2', N'Square Feet', GETDATE());

    INSERT INTO Production.UnitMeasureVALUES (N'F2', N'Square Feet', GETDATE()),(N'Y2', N'Square Yards', GETDATE());

    Inserting Multiple Rows of Data

  • 7/31/2019 2778A_06

    7/35

    Inserting Values into Identity Columns

    CREATE TABLE dbo.T1 ( column_1 intIDENTITY, column_2 VARCHAR(30));GO

    INSERT T1 VALUES ('Row #1');INSERT T1 (column_2) VALUES ('Row #2');GOSET IDENTITY_INSERT T1 ON;GOINSERT INTO T1 (column_1,column_2)

    VALUES (-99, 'Explicit identityvalue');

    GOSELECT column_1, column_2FROM T1;

    column_listand VALUES must be used to insert valuesinto an identity column, and the SETIDENTITY_INSERT option must be ON for the table

  • 7/31/2019 2778A_06

    8/35

    INSERT and the OUTPUT Clause

    Using OUTPUT in an INSERT statement returns informationfrom each row affected by the INSERT statement

    INSERT SomeTableOUTPUT 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 @MyTableVarVALUES (N'Operator error', GETDATE());

    Example Query:

    Syntax:

  • 7/31/2019 2778A_06

    9/35

    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

  • 7/31/2019 2778A_06

    10/35

    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

  • 7/31/2019 2778A_06

    11/35

    DELETE Fundamentals

    DELETE table_or_view

    FROM table_sources

    WHERE search_condition

    The DELETE statement removes one or more rows in atable or view

    DELETE removes rows from the table_or_viewparameter that meet thesearch condition

    table_sources can be used to specify additional tablesor views that can be used by the WHERE clause

    DELETE Syntax:

  • 7/31/2019 2778A_06

    12/35

    DELETE Statement Definitions

    DELETE FROM SomeTable;

    DELETE FROM SomeTableWHERE SomeColumn IN

    (Subquery Definition);

    DELETE TOP (#) PERCENTFROM SomeTable;

    DELETE with no WHERE clause

    DELETE using a Subquery

    DELETE using TOP

    DELETE FROM Sales.SalesPerson;

    DELETE FROM

    Sales.SalesPersonQuotaHistoryWHERE SalesPersonID IN(SELECT SalesPersonIDFROM Sales.SalesPersonWHERE SalesYTD >

    2500000.00);

    DELETE TOP (2.5) PERCENTFROMProduction.ProductInventory;

  • 7/31/2019 2778A_06

    13/35

    Defining and Using the TRUNCATE Statement

    TRUNCATE TABLE HumanResources.JobCandidate;

    TRUNCATE TABLE[ { database_name.[ schema_name ]. | schema_name . } ]table_name

    [ ; ]

    You cannot use TRUNCATE TABLE on tables thatare referenced by a FOREIGN KEY constraint

    TRUNCATE TABLE Syntax

    TRUNCATE TABLE Example

  • 7/31/2019 2778A_06

    14/35

    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 overDELETE:

    DELETE FROM Sales.SalesPerson;

    TRUNCATE TABLE Sales.SalesPerson;

  • 7/31/2019 2778A_06

    15/35

    DELETE and the OUTPUT Clause

    Using OUTPUT in a DELETE statement removes a row from atable and returns the deleted values to a result set

    DELETE SomeTableOUTPUT column_list

    DELETE Production.CultureOUTPUT DELETED.*;

    Example Query:

    Syntax:

    CultureID Name ModifiedDate---------------------------------------Ar Arabic 1998-06-01En English 1998-06-01

  • 7/31/2019 2778A_06

    16/35

    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

  • 7/31/2019 2778A_06

    17/35

  • 7/31/2019 2778A_06

    18/35

    UPDATE Fundamentals

    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 canchange 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:

  • 7/31/2019 2778A_06

    19/35

    UPDATE Statement Definitions

    UPDATE SomeTableSET Column = Value

    UPDATE SomeTableSET Column = ValueWHERE SearchExpression

    Simple UPDATE Statement

    UPDATE with a WHERE clause

    UPDATE Sales.SalesPersonSET Bonus = 6000;

    UPDATE Production.ProductSET Color = NMetallic RedWHERE Name LIKE NRoad-250%

    AND Color = NRed;

    UPDATE Sales.SalesPerson

    SET Bonus = Bonus * 2;

  • 7/31/2019 2778A_06

    20/35

    Updating with Information from Another Table

    UPDATE SomeTableSET Column = ValueFROM SomeSubquery

    UPDATE using a Subquery

    UPDATE Sales.SalesPersonSET SalesYTD = SalesYTD + SubTotal

    FROM Sales.SalesPerson AS spJOIN Sales.SalesOrderHeader AS soON sp.BusinessEntityID = so.SalesPersonIDAND so.OrderDate = (SELECT MAX(OrderDate)

    FROM Sales.SalesOrderHeaderWHERE SalesPersonID =

    sp.BusinessEntityID);

    SalesYTD--------------677558.46534557045.0459

    BeforeSalesYTD--------------721382.4884593234.5123

    After

  • 7/31/2019 2778A_06

    21/35

    UPDATE and the OUTPUT Clause

    Using OUTPUT in an UPDATE statement returns informationfrom each row affected by the UPDATE statement

    UPDATE SomeTableOUTPUT dml_select_list FROM table_sourceWHERE search_condition

    DECLARE @NewTableVar table ( Dollars money );UPDATE Sales.SalesPersonSET Bonus = 10000OUTPUT INSERTED.Bonus INTO @NewTableVar;

    SELECT DollarsFROM @NewTableVar;

    Syntax:

    Dollars--------10000.0010000.00...(17 row(s) affected)

  • 7/31/2019 2778A_06

    22/35

    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

  • 7/31/2019 2778A_06

    23/35

    Lesson 4: Overview of Transactions

    Transaction Fundamentals

    Transactions and the Database Engine

    Basic Transaction Statement Definitions

    What are Transaction Isolation Levels?

    Using Nested Transactions

  • 7/31/2019 2778A_06

    24/35

    Transaction Fundamentals

    A Transaction:

    Is a sequence of operations performed as a singlelogical 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 madeby any other concurrent transactions

    Durability persists even after system failure

  • 7/31/2019 2778A_06

    25/35

    Transactions and the Database Engine

    The Database Engine provides:

    Locking facilities that preserve transaction isolation

    Transaction Isolation Levels control when locks aretaken and how long they are held

    Logging facilities that ensure transaction durability

    Write-ahead log (WAL) guarantees no datamodifications are written before they are logged

    Checkpoints write records to a data file and contain listsof all active transactions

    Transaction management features that enforcetransaction atomicity and consistency

    Transactions must be successfully completed or theirmodifications are undone

  • 7/31/2019 2778A_06

    26/35

    Basic Transaction Statement Definitions

    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 ...;

    COMMIT TRAN T1;

    ROLLBACK { TRAN | TRANSACTION } [transaction_name | @tran_name_variable |savepoint_name | @savepoint_variable ]

    ROLLBACK TRANSACTION

    ROLLBACK TRAN T1;

  • 7/31/2019 2778A_06

    27/35

  • 7/31/2019 2778A_06

    28/35

    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 affectthe locks acquired to protect data modifications

    SET TRANSACTION ISOLATION LEVEL ;

    Syntax

    The levels are READ UNCOMMITTED, READCOMMITTED, REPEATABLE READ, SNAPSHOT, andSERIALIZABLE

    Demonstration: Setting Transaction Isolation

  • 7/31/2019 2778A_06

    29/35

    Demonstration: Setting Transaction IsolationLevels

    In this demonstration, you will see how to:

    Set a Transaction Isolation Level

  • 7/31/2019 2778A_06

    30/35

    CREATE TABLE TestTrans(Cola INT PRIMARY KEY,Colb CHAR(3) NOT NULL);

    GOCREATE PROCEDURE TransProc @PriKey INT, @CharCol CHAR(3) ASBEGIN TRANSACTION InProcINSERT INTO TestTrans VALUES (@PriKey, @CharCol)

    INSERT INTO TestTrans VALUES (@PriKey + 1, @CharCol)COMMIT TRANSACTION InProc;GOBEGIN TRANSACTION OutOfProc; /* Starts a transaction */GOEXEC TransProc 1, 'aaa';GOROLLBACK TRANSACTION OutOfProc; /* Rolls back the outer

    transaction */GOEXECUTE TransProc 3,'bbb';GOSELECT * FROM TestTrans;GO

    Using Nested Transactions

    Explicit transactions can be nested to support

    transactions in stored procedures

    Cola Colb------------1 bb2 bb

  • 7/31/2019 2778A_06

    31/35

    Demonstration: Using Nested Transactions

    In this demonstration, you will see how to:

    Create a Nested Transaction

  • 7/31/2019 2778A_06

    32/35

    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 machine NY-SQL-01User name Administrator

    Password Pa$$w0rd

    Estimated time: 60 minutes

  • 7/31/2019 2778A_06

    33/35

    Lab Scenario

    You are a database developer at Adventure Works. You havebeen asked by the senior database administrator to add,

    delete, and change rows on several tables in theAdventureWorks2008 database. You must be sure to followthe specifications that the senior database administrator hasprovided you closely so you do not insert incorrect data intothe tables, change data unnecessarily, or delete vital companydata.

  • 7/31/2019 2778A_06

    34/35

    Lab Review

    Why are values for column names listed in the same orderas columns on the table when using the INSERT

    statement?

    How can we verify that rows have been deleted after usingthe DELETE statement?

    How can we write an UPDATE statement to ensure that all

    rows of a table are affected?

  • 7/31/2019 2778A_06

    35/35

    Module Review and Takeaways

    Review Questions

    Best Practices