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 7: Adding More to Our Queries<br />

204<br />

So, the question probably quickly rises in your mind, “Hey, if CONVERT does everything that CAST<br />

does, and CONVERT also does date conversions, why would I ever use CAST?” I have a simple answer<br />

for that — ANSI/ISO compliance. CAST is ANSI/ISO-compliant, but CONVERT isn’t — it’s that simple.<br />

Let’s take a look for the syntax for each.<br />

CAST (expression AS data_type)<br />

CONVERT(data_type, expression[, style])<br />

With a little flip-flop on which goes first and the addition of the formatting option on CONVERT (with the<br />

style argument), they have basically the same syntax.<br />

CAST and CONVERT can deal with a wide variety of data-type conversions that you’ll need to do when<br />

<strong>SQL</strong> <strong>Server</strong> won’t do it implicitly for you. For example, converting a number to a string is a very common<br />

need. To illustrate:<br />

SELECT ‘The Customer has an Order numbered ‘ + SalesOrderID<br />

FROM Sales.SalesOrderHeader<br />

WHERE CustomerID = 29825;<br />

will yield an error:<br />

Msg 245, Level 16, State 1, Line 1<br />

Conversion failed when converting the varchar value ‘The Customer has an Order<br />

numbered ‘ to data type int.<br />

But change the code to convert the number first:<br />

SELECT ‘The Customer has an Order numbered ‘ + CAST(SalesOrderID AS varchar)<br />

FROM Sales.SalesOrderHeader<br />

WHERE CustomerID = 29825;<br />

And you get a much different result:<br />

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

The Customer has an Order numbered 43659<br />

The Customer has an Order numbered 44305<br />

The Customer has an Order numbered 45061<br />

The Customer has an Order numbered 45779<br />

The Customer has an Order numbered 46604<br />

The Customer has an Order numbered 47693<br />

The Customer has an Order numbered 48730<br />

The Customer has an Order numbered 49822<br />

The Customer has an Order numbered 51081<br />

The Customer has an Order numbered 55234<br />

The Customer has an Order numbered 61173<br />

The Customer has an Order numbered 67260<br />

(12 row(s) affected)

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

Saved successfully!

Ooh no, something went wrong!