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 />

74<br />

/* This next statement is going to use code to change the “current” database<br />

** to AdventureWorks<strong>2008</strong>. This makes certain, right in the code that we are going<br />

** to the correct database.<br />

*/<br />

USE AdventureWorks<strong>2008</strong>;<br />

/* This next statement declares our working table.<br />

** This particular table is actually a variable we are declaring on the fly.<br />

*/<br />

DECLARE @MyTable Table<br />

(<br />

SalesOrderID int,<br />

CustomerID char(5)<br />

);<br />

/* Now that we have our table variable, we’re ready to populate it with data<br />

** from our SELECT statement. Note that we could just as easily insert the<br />

** data into a permanent table (instead of a table variable).<br />

*/<br />

INSERT INTO @MyTable<br />

SELECT SalesOrderID, CustomerID<br />

FROM AdventureWorks<strong>2008</strong>.Sales.SalesOrderHeader<br />

WHERE SalesOrderID BETWEEN 44000 AND 44010;<br />

-- Finally, let’s make sure that the data was inserted like we think<br />

SELECT *<br />

FROM @MyTable;<br />

This should yield you results that look like this:<br />

(11 row(s) affected)<br />

SalesOrderID CustomerID<br />

------------ ----------<br />

44000 27918<br />

44001 28044<br />

44002 14572<br />

44003 19325<br />

44004 28061<br />

44005 26629<br />

44006 16744<br />

44007 25555<br />

44008 27678<br />

44009 27759<br />

44010 13680<br />

(11 row(s) affected)<br />

The first instance of (11 row(s) affected) we see is the effect of the INSERT...SELECT statement at<br />

work. Our SELECT statement returned three rows, so that’s what got INSERTed into our table. We then<br />

used a straight SELECT statement to verify the INSERT.

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

Saved successfully!

Ooh no, something went wrong!