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 11: Writing Scripts and Batches<br />

Setting Variables Using SET<br />

SET is usually used for setting variables in the fashion that you would see in more procedural languages.<br />

Examples of typical uses would be:<br />

SET @TotalCost = 10<br />

SET @TotalCost = @UnitCost * 1.1<br />

Notice that these are all straight assignments that use either explicit values or another variable. With a<br />

SET, you cannot assign a value to a variable from a query — you have to separate the query from the<br />

SET. For example:<br />

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

DECLARE @Test money;<br />

SET @Test = MAX(UnitPrice) FROM [Order Details];<br />

SELECT @Test;<br />

causes an error, but:<br />

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

DECLARE @Test money;<br />

SET @Test = (SELECT MAX(UnitPrice) FROM Sales.SalesOrderDetail);<br />

SELECT @Test;<br />

works just fine.<br />

Although this latter syntax works, by convention, code is never implemented this way. Again, I don’t<br />

know for sure why it’s “just not done that way,” but I suspect that it has to do with readability — you<br />

want a SELECT statement to be related to retrieving table data, and a SET to be about simple variable<br />

assignments.<br />

Setting Variables Using SELECT<br />

SELECT is usually used to assign variable values when the source of the information you’re storing in<br />

the variable is from a query. For example, our last illustration would be typically done using a SELECT:<br />

328<br />

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

DECLARE @Test money;<br />

SELECT @Test = MAX(UnitPrice) FROM Sales.SalesOrderDetail;<br />

SELECT @Test;<br />

Notice that this is a little cleaner (it takes less verbiage to do the same thing).<br />

So again, the convention on when to use which goes like this:<br />

❑ Use SET when you are performing a simple assignment of a variable — where your value is<br />

already known in the form of an explicit value or some other variable.<br />

❑ Use SELECT when you are basing the assignment of your variable on a query.

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

Saved successfully!

Ooh no, something went wrong!