17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3: The Foundation Statements of T-<strong>SQL</strong><br />

Note that if you try running a SELECT against @MyTable by itself (that is, outside<br />

this script), you’re going to get an error. @MyTable is a declared variable and it exists<br />

only as long as our batch is running. After that, it is automatically destroyed.<br />

It’s also worth noting that we could have used what’s called a temporary table. This<br />

is similar in nature, but doesn’t work in quite the same way. We will revisit temp<br />

tables and table variables in Chapters 11 through 13.<br />

Changing What Y ou’ve Got with the<br />

UPDATE Statement<br />

The UPDATE statement, like most <strong>SQL</strong> statements, does pretty much what it sounds like it does — it<br />

updates existing data. The structure is a little bit different from a SELECT, although you’ll notice definite<br />

similarities. Like the INSERT statement, it has a fairly complex set of options, but a more basic version<br />

that will meet the vast majority of your needs.<br />

The full syntax supports the same TOP and similar predicates that were supported under SELECT and INSERT:<br />

UPDATE [TOP ( ) [PERCENT] ] <br />

SET = [.WRITE(, , )]<br />

[, = [.WRITE(, , )]]<br />

[ OUTPUT ]<br />

[FROM ]<br />

[WHERE ]<br />

Let’s look at the more basic syntax:<br />

UPDATE <br />

SET = [, = ]<br />

[FROM ]<br />

[WHERE ]<br />

An UPDATE can be created from multiple tables, but can affect only one table. What do I mean by that?<br />

Well, we can build a condition, or retrieve values from any number of different tables, but only one table<br />

at a time can be the subject of the UPDATE action. Don’t sweat this one too much. We haven’t looked at<br />

joining multiple tables yet (next chapter folks!), so we won’t get into complex UPDATE statements here.<br />

For now, we’ll look at simple updates.<br />

Let’s start by doing some updates to the data that we inserted in the INSERT statement section. Let’s<br />

rerun that query to look at one row of inserted data. (Don’t forget to switch back to the pubs database.):<br />

SELECT *<br />

FROM Stores<br />

WHERE StoreCode = ‘TEST’;<br />

75

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!