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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

While <strong>SQL</strong> <strong>Server</strong> is nice enough to let us UPDATE pretty much any column (there are<br />

a few that we can’t, such as timestamps), be very careful about updating primary<br />

keys. Doing so puts you at very high risk of orphaning other data (data that has a reference<br />

to the data you’re changing).<br />

For example, the StoreCode field in the Stores table is a primary key. If we decide<br />

to change StoreCode 10 to 35 in Stores, then any data in the Sales table that relates to<br />

that store may be orphaned and lost if the StoreCode value in all of the records relating<br />

to StoreCode 10 is not also updated to 35. As it happens, there is a constraint that references<br />

the Stores table, so <strong>SQL</strong> <strong>Server</strong> would prevent such an orphaning situation in<br />

this case (we’ll investigate constraints in Chapter 7), but updating primary keys is<br />

risky at best.<br />

The DELETE Statement<br />

The version of the DELETE statement that we’ll cover in this chapter may be one of the easiest statements<br />

of them all. Even in the more complex syntax, there’s no column list, just a table name and (usually) a<br />

WHERE clause. The full version looks like this:<br />

DELETE [TOP ( ) [PERCENT] ] [FROM] <br />

[ OUTPUT ]<br />

[FROM ]<br />

[WHERE | CURRENT OF [GLOBAL] ]<br />

The basic syntax couldn’t be much easier:<br />

DELETE <br />

[WHERE ]<br />

The WHERE clause works just like all the WHERE clauses we’ve seen thus far. We don’t need to provide a<br />

column list because we are deleting the entire row. (You can’t delete half a row, for example.)<br />

Because this is so easy, we’ll perform only a couple of quick DELETEs that are focused on cleaning up the<br />

INSERTs that we performed earlier in the chapter. First, let’s run a SELECT to make sure the first of those<br />

rows is still there:<br />

SELECT *<br />

FROM Stores<br />

WHERE StoreCode = ‘TEST’;<br />

If you haven’t already deleted it, you should come up with a single row that matches what we added<br />

with our original INSERT statement. Now let’s get rid of it:<br />

DELETE Stores<br />

WHERE StoreCode = ‘TEST’;<br />

77

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

Saved successfully!

Ooh no, something went wrong!