DATABASE

SQL Server 2008 : Working with DML Queries - Using the UPDATE Statement (part 1)

1/16/2011 9:06:01 AM
The UPDATE statement updates existing rows in an existing table or updateable view. Let’s examine the syntax of the UPDATE statement. The elements shown in Example 1 appear most commonly in the UPDATE statement.
Example 1. UPDATE Statement—Core Elements
UPDATE
[ TOP (n) [PERCENT] ]
table_or_view
SET
{ column_to_update = { new_value | DEFAULT | NULL }
| column_to_update { .WRITE (new_value, @Offset, @Length) }
| @variable = new_value
| @variable = column_to_update = new_value
| column_to_update { += | -= | *= | /= | %= | &= | ^= | |= } new_value
| @variable { += | -= | *= | /= | %= | &= | ^= | |= } new_value
| @variable = column_to_update { += | -= | *= | /= | %= | &= | ^= | |= } new_
value }
[FROM ...
WHERE ... ]

The table_or_view is the name of the table or view in which you are updating rows. If you are using a view for your UPDATE statement, this view must be updateable. Updateable views are based upon a single source table. You could also substitute a table-valued variable as the table_or_view.

The TOP (n) [PERCENT] clause serves the same purpose as it does in the INSERT statement. Only the top n, or top n percent of rows will be updated, if this clause is specified.

The SET keyword specifies the list of columns or variables that will be updated. The column_to_update is the name of the column containing the data that should be changed. Column_to_update must be a column from the table_or_view. Identity columns cannot be updated.

The new_value is a literal value, a variable, a subselect statement (enclosed within parentheses), or any scalar expression. When the UPDATE statement completes, the column_to_update or @variable value will be set to the new_value.

The FROM is essentially the filter criteria for defining what data should be updated, and what it should be updated to. If this part of the UPDATE statement is omitted, all data in the table or view will be updated. Ensure that you specify an alias if the table or view you are trying to update is mentioned more than once in the FROM clause.

The WHERE clause specifies an additional filter for data that should be updated.


The column can be set to its new value using not just the familiar equals to (=) operator, but also a variety of other assignment operators. Table 1 lists assignment operators available. Use these operators with the SET clause of the UPDATE statement.
Table 1. Assignment Operators
Operator SignUse
=Assign
+=Add and assign
−=Subtract and assign
*=Multiply and assign
/=Divide and assign
%=Modulo and assign
&=Bitwise AND and assign
^=Bitwise XOR and assign
|=Bitwise OR and assign

UPDATE Statement Examples

Examples 2 through 4 demonstrate the most common uses of the UPDATE statement. Feel free to run these examples against the AdventureWorks database. Performing the examples yourself will give you a better understanding of how the UPDATE statement is used.


Example 2. Using the UPDATE...SET...WHERE Statement
SELECT DISTINCT Color from Production.Product
GO

--Change all product with NULL color to show 'N/A'
USE AdventureWorks
GO

UPDATE Production.Product
SET Color = 'N/A'
WHERE
Color is NULL
GO
SELECT DISTINCT Color from Production.Product
GO

Example 3. Using the UPDATE...SET...FROM...WHERE Statement with Ambiguous Table Names
-- List all employees managed by David Bradley, along with their vacation
hours
SELECT Employee.VacationHours, Person.Contact.FirstName + ' ' + Person.
Contact.LastName as EmployeeName,
ManagerContact.FirstName + ' ' + ManagerContact.LastName as ManagerName
FROM HumanResources.Employee
join Person.Contact ON HumanResources.Employee.ContactID = Person.Contact.
ContactID
join HumanResources.Employee as Manager ON HumanResources.Employee.ManagerID =
Manager.EmployeeID
join Person.Contact as ManagerContact ON Manager.ContactID = ManagerContact.
ContactID
WHERE ManagerContact.FirstName = 'David' AND ManagerContact.LastName =
'Bradley'
GO

-- Add 10 vacation hours to all employees managed by David Bradley
UPDATE Humanresources.Employee
SET VacationHours += 10
FROM HumanResources.Employee
join Person.Contact ON HumanResources.Employee.ContactID = Person.Contact.
ContactID
join HumanResources.Employee as Manager ON HumanResources.Employee.ManagerID =
Manager.EmployeeID
join Person.Contact as ManagerContact ON Manager.ContactID = ManagerContact.
ContactID
WHERE ManagerContact.FirstName = 'David' AND ManagerContact.LastName =
'Bradley'
GO

-- List all employees managed by David Bradley, along with their vacation
hours
-- Ensure that the hours have been updated by the previous statement
SELECT Employee.VacationHours, Person.Contact.FirstName + ' ' + Person.
Contact.LastName as EmployeeName,
ManagerContact.FirstName + ' ' + ManagerContact.LastName as ManagerName
FROM HumanResources.Employee
join Person.Contact ON HumanResources.Employee.ContactID = Person.Contact.
ContactID
join HumanResources.Employee as Manager ON HumanResources.Employee.ManagerID =
Manager.EmployeeID
join Person.Contact as ManagerContact ON Manager.ContactID = ManagerContact.
ContactID
WHERE ManagerContact.FirstName = 'David' AND ManagerContact.LastName =
'Bradley'
GO

Example 4. Using the UPDATE...SET...FROM...WHERE Statement with Ambiguous Table Names
-- Show all products by cost, only from subcategies that contains 'Bikes'
-- Show the ListPrice for each Product
SELECT Product.Name, Product.StandardCost, Product.ListPrice,
ProductSubcategory.Name
FROM Production.Product JOIN Production.ProductSubcategory
ON ProductSubcategory.ProductSubcategoryID = Product.ProductSubcategoryID
WHERE ProductSubcategory.Name like '%Bikes%'
ORDER BY Product.StandardCost DESC
GO

-- Increase the ListPrice by 20% for the 10 highest-cost products, from
subcategies that contains 'Bikes'
UPDATE Production.Product
SET Product.ListPrice *= 1.15
WHERE Product.ProductID in
(SELECT TOP (10) ProductID
FROM Production.Product JOIN Production.ProductSubcategory
ON ProductSubcategory.ProductSubcategoryID = Product.ProductSubcategoryID
WHERE ProductSubcategory.Name like '%Bikes%'

ORDER BY Product.StandardCost DESC)
GO

-- Show the ListPrice for each Product after the Increase
SELECT Product.Name, Product.StandardCost, Product.ListPrice,
ProductSubcategory.Name
FROM Production.Product JOIN Production.ProductSubcategory
ON ProductSubcategory.ProductSubcategoryID = Product.ProductSubcategoryID
WHERE ProductSubcategory.Name like '%Bikes%'
ORDER BY Product.StandardCost DESC
GO



Other  
  •  Azure Programming Considerations
  •  Programming with SQL Azure : Record Navigation in WCF Data Services
  •  Defensive Database Programming with SQL Server : TRY...CATCH Gotchas (part 2) - TRY...CATCH blocks cannot catch all errors
  •  Defensive Database Programming with SQL Server : TRY...CATCH Gotchas (part 1) - Re-throwing errors
  •  SQL Server 2008 : Working with DML Queries - Using the INSERT Statement (part 2)
  •  SQL Server 2008 : Working with DML Queries - Using the INSERT Statement (part 1) - Using the INSERT Statement with the VALUES Clause
  •  Programming Microsoft SQL Server 2005: Using the Data Mining Wizard and Data Mining Designer (part 7) - Nested Tables
  •  Programming Microsoft SQL Server 2005: Using the Data Mining Wizard and Data Mining Designer (part 6) - Validating and Comparing Mining Models
  •  Programming Microsoft SQL Server 2005: Using the Data Mining Wizard and Data Mining Designer (part 5) - Viewing Mining Models
  •  Programming Microsoft SQL Server 2005: Using the Data Mining Wizard and Data Mining Designer (part 4) - Deploying and Processing Data Mining Objects
  •  
    Video
    Top 10
    SG50 Ferrari F12berlinetta : Prancing Horse for Lion City's 50th
    The latest Audi TT : New angles for TT
    Era of million-dollar luxury cars
    Game Review : Hearthstone - Blackrock Mountain
    Game Review : Battlefield Hardline
    Google Chromecast
    Keyboards for Apple iPad Air 2 (part 3) - Logitech Ultrathin Keyboard Cover for iPad Air 2
    Keyboards for Apple iPad Air 2 (part 2) - Zagg Slim Book for iPad Air 2
    Keyboards for Apple iPad Air 2 (part 1) - Belkin Qode Ultimate Pro Keyboard Case for iPad Air 2
    Michael Kors Designs Stylish Tech Products for Women
    REVIEW
    - First look: Apple Watch

    - 3 Tips for Maintaining Your Cell Phone Battery (part 1)

    - 3 Tips for Maintaining Your Cell Phone Battery (part 2)
    Popular Tags
    Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Exchange Server Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe Photoshop CorelDRAW X5 CorelDraw 10 windows Phone 7 windows Phone 8 Iphone