1 / 27

Brian Alderman | MCT, CEO / Founder of MicroTechPoint

06 | Modifying Data in SQL Server. Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager. Course Topics. DML statements (INSERT, UPDATE, and DELETE) Working with defaults, constraints, and triggers Using the OUTPUT clause.

Download Presentation

Brian Alderman | MCT, CEO / Founder of MicroTechPoint

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager

  2. Course Topics

  3. DML statements (INSERT, UPDATE, and DELETE) Working with defaults, constraints, and triggers Using the OUTPUT clause Module Overview

  4. DDL Statements

  5. Using INSERT to add data • The INSERT...VALUES statement inserts a single row by default • Table and row constructors add multi-row capability to INSERT...VALUES INSERT INTO Production.UnitMeasure (Name, UnitMeasureCode, ModifiedDate) VALUES (N'Square Yards', N'Y2', GETDATE()); GO INSERT INTO Production.UnitMeasure (Name, UnitMeasureCode, ModifiedDate) VALUES (N'SquareFeet', N‘F2', GETDATE()), (N'SquareInches', N‘I2', GETDATE());

  6. Using INSERT with SELECT and EXEC • INSERT...SELECT is used to insert the result set of a query into an existing table • INSERT...EXEC is used to insert the result of a stored procedure or dynamic SQL expression into an existing table INSERTINTOProduction.UnitMeasure (Name, UnitMeasureCode, ModifiedDate) SELECTName, UnitMeasureCode, ModifiedDate FROMSales.TempUnitTable WHEREModifiedDate<'20080101'; INSERTINTOProduction.UnitMeasure (Name, UnitMeasureCode, ModifiedDate) EXECProduction.Temp_UOM @numrows = 5, @catid=1;

  7. Using SELECT INTO • SELECT...INTO is similar to INSERT...SELECT but SELECT...INTO creates a new table each time the statement is executed • Copies column names, data types, and nullability • Does not copy constraints or indexes SELECTName, UnitMeasureCode, ModifiedDate INTOProduction.TempUOMTable FROMProduction.UnitMeasure WHEREorderdate<'20080101';

  8. Using IDENTITY • IDENTITY property of a column generates sequential numbers automatically for insertion into a table • Can specify optional set seed and increment values • Only one column in a table may have IDENTITY property defined • IDENTITY column is omitted in INSERT statements • Functions provided to retrieve last generated value • Creates a table with using the IDENTITY property with a starting number of 100 and incremented by 10 as each row is added CREATETABLEProduction.IdentityProducts( productid intIDENTITY(100,10)NOT NULL, productname nvarchar(40) NOT NULL, categoryid intNOT NULL, unitprice moneyNOT NULL)

  9. Using SEQUENCES • Sequence objects new in SQL Server 2012 • Independent objects in database • More flexible than the IDENTITY property • Can be used as default value for a column • Manage with CREATE/ALTER/DROP statements • Retrieve value with the NEXT VALUE FOR clause -- Define a sequence CREATESEQUENCE dbo.InvoiceSeqASINTSTARTWITH5 INCREMENTBY5; -- Retrieve next available value from sequence SELECTNEXTVALUEFORdbo.InvoiceSeq;

  10. Using UPDATEto modify data • Updates all rows in a table or view • Set can be filtered with a WHERE clause • Set can be defined with a JOIN clause • Only columns specified in the SET clause are modified • Updates the ModifiedDate using a the GETDATE function for the record that has ‘M2’ in the UnitMeasureCode • If no WHERE clause is specified, all records in the Production.UnitMeasure will be updated UPDATEProduction.UnitMeasure SETModifiedDate=(GETDATE()) WHEREUnitMeasureCode=‘M2’

  11. Using MERGE to modify data • MERGE modifies data based on one of the following conditions • When the source matches the target • When the source has no match in the target • When the target has no match in the source MERGEINTOschema_name.table_nameASTargetTbl USING (SELECT<select_list>)ASSourceTbl ON (TargetTbl.col1=SourceTbl.col1) WHENMATCHEDTHEN UPDATESETcol2=SourceTbl.col2 WHENNOTMATCHEDTHEN INSERT (<column_list>) VALUES (<value_list>);

  12. Using DELETE to remove data • DELETE operates on a set • Set may be filtered with a WHERE clause • Deletion of each row is logged in database's transaction log • DELETE may be rolled back if statement issued within a user-defined transaction or if an error is encountered • If no WHERE clause is specified, all records in the Production.UnitMeasure will be deleted DELETEFROMProduction.UnitMeasure WHEREUnitMeasureCode=‘Y2’;

  13. Using TRUNCATE TABLE to remove all data • TRUNCATE TABLE clears the entire table • Storage is physically deallocated, rows not individually removed • Minimally logged • Can be rolled back if TRUNCATE issued within a transaction • TRUNCATE TABLE will fail if the table is referenced by a foreign key constraint in another table TRUNCATETABLEProduction.UnitMeasure

  14. Demo Inserting, updating, and deleting data

  15. Constraints and Triggers

  16. PRIMARY KEY constraint • A PRIMARY KEYis an important concept of designing a database table as it provides an attribute or set of attributes used to uniquely identify each row in the table • A table can only have one primary key which is created using a primary key constraint and enforced by creating a unique index on the primary key columns • A column that participates in the primary key constraint cannot accept null values • To add a PRIMARY KEY constraint to an existing table use the following command ALTER TABLE Production.TransactionHistoryArchive ADD CONSTRAINT PK_TransactionHistoryArchive_TransactionID PRIMARY KEY CLUSTERED (TransactionID);

  17. FOREIGN KEY constraint • A FOREIGN KEY is a column or combination of columns that are used to establish a link between data in two tables. The columns used to create the primary key in one table are also used to create the foreign key constraint and can be used to reference data in the same table or in another table • A foreign key does not have to reference a primary key, it can be defined to reference a unique constraint in either the same table or in another table • To add a FOREIGN KEY constraint to an existing table use the following command ALTER TABLE Sales.SalesOrderHeaderSalesReason ADD CONSTRAINT FK_SalesReason FOREIGN KEY (SalesReasonID) REFERENCESSales.SalesReason (SalesReasonID) ON DELETE CASCADE ON UPDATE CASCADE ;

  18. UNIQUE constraints • A UNIQUE constraint is created to ensure no duplicate values are entered in specific columns that do not participate in a primary key • Creating a UNIQUE constraint automatically creates a corresponding unique index • To create a UNIQUE constraint while creating a table use the following command CREATE TABLE Production.TransactionHistoryArchive4 (TransactionIDint NOT NULL, CONSTRAINTAK_TransactionIDUNIQUE(TransactionID) );

  19. CHECK constraints • A CHECK constraint is created in a table to specify the data values that are acceptable in one or more columns • To create a CHECK constraint after creating a table use the following command ALTER TABLE DBO.NewTable ADDZipCodeint NULL CONSTRAINTCHK_ZipCode CHECK (ZipCode LIKE'[0-9][0-9][0-9][0-9][0-9]‘);

  20. DEFAULT constraints • A DEFAUT constraint is a special case of a column default that is applied when an INSERT statement doesn't explicitly assign a particular value. In other words, the column default is what the column will get as a value by default • To create a DEFAULT constraint on an existing table use the following command ALTER TABLE Sales.CountryRegionCurrency ADD CONSTRAINT Default_Country DEFAULT‘USA’ FOR CountryRegionCode

  21. DML triggers • A DMLtrigger is a special type of stored procedure that automatically fires when any valid DML event takes place regardless of whether or not any rows are affected • DML triggers can include complex T-SQL statements used to enforce business rules and provide data integrity when an INSERT, UPDATE, or DELETE command is executed • The following trigger will prints a message to the client when anyone tries to add or change data in the Customer table CREATE TRIGGER reminder1 ONSales.Customer AFTER INSERT, UPDATE AS RAISERROR ('Notify Customer Relations', 16, 10);

  22. OUTPUT clause • The OUTPUT clauseis used to return information from, or expressions based on, each row affected by an INSERT, UPDATE, DELETE, or MERGE statement. These results can be returned to the processing application for use in such things as confirmation messages or archiving • The following example deletes all rows in the ShoppingCartItem table. The clause OUTPUT deleted.* specifies that all columns in the deleted rows, be returned to the calling application which in this case was the Query Editor DELETESales.ShoppingCartItemOUTPUT DELETED.* WHERE ShoppingCartID = 20621; --Verify the rows in the table matching the WHERE clause have been deleted. SELECTCOUNT(*) AS [Rows in Table] FROMSales.ShoppingCartItem WHEREShoppingCartID = 20621;

  23. Demo Working with constraints and triggers

  24. Summary • To add data to a table in SQL Server you can use one of several options including • INSERT • INSERT INTO using SELECT or EXEC • SELECT INTO • To change the values of data in a SQL Server table you can use the UPDATE or MERGE commands • To remove data from a SQL Server table you can use the DELETE or the TRUNCATE TABLE commands. The DELETE always you to remove one or more rows of data where the TRUNCATE TABLE deletes all rows in the table

  25. Summary • To have an number automatically increment as rows are being added in your SQL Server table you can use either the IDENTITY property or the SEQUENCE property. Both of them allow you to define the SEED and INCREMENT property • IDENTITY property • SEQUENCE property CREATETABLEProduction.IdentityProducts( productid intIDENTITY(100,10)NOT NULL, productname nvarchar(40) NOT NULL, categoryid intNOT NULL, unitprice moneyNOT NULL) -- Define a sequence CREATESEQUENCE dbo.InvoiceSeqASINTSTARTWITH5 INCREMENTBY5; -- Retrieve next available value from sequence SELECTNEXTVALUEFORdbo.InvoiceSeq;

  26. Summary Constraints can be used to control the behavior of SQL Server when data is added, modified, or deleted. There are five constraints types that you can use: PRIMARY KEY FOREIGN KEY UNIQUE CHECK DEFAULT DML triggers are T-SQL statements used to enforce business rules and provide data integrity when an INSERT, UPDATE, or DELETE command is executed CREATE TRIGGER reminder1 ONSales.Customer AFTER INSERT, UPDATE AS RAISERROR ('Notify Customer Relations', 16, 10);

More Related