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.

The conversions can actually get a little less intuitive also. For example, what if you wanted to convert a<br />

timestamp column into a regular number? A timestamp is just a binary number, so the conversion isn’t<br />

any really big deal:<br />

CREATE TABLE ConvertTest<br />

(<br />

ColID int IDENTITY,<br />

ColTS timestamp<br />

);<br />

GO<br />

INSERT INTO ConvertTest<br />

DEFAULT VALUES;<br />

SELECT ColTS AS Uncoverted, CAST(ColTS AS int) AS Converted<br />

FROM ConvertTest;<br />

This yields something like (your exact numbers will vary):<br />

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

Uncoverted Converted<br />

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

0x00000000000000C9 201<br />

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

We can also convert dates:<br />

SELECT OrderDate, CAST(OrderDate AS varchar) AS Converted<br />

FROM Sales.SalesOrderHeader<br />

WHERE SalesOrderID = 43663;<br />

This yields something similar to (your exact format may change depending on system date configuration):<br />

OrderDate Converted<br />

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

2001-07-01 00:00:00.000 Jul 1 2001 12:00AM<br />

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

Notice that CAST can still do date conversion; you just don’t have any control over the formatting as you<br />

do with CONVERT. For example:<br />

SELECT OrderDate, CONVERT(varchar(12), OrderDate, 111) AS Converted<br />

FROM Sales.SalesOrderHeader<br />

WHERE SalesOrderID = 43663;<br />

This yields:<br />

OrderDate Converted<br />

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

2001-07-01 00:00:00.000 2001/07/01<br />

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

Chapter 7: Adding More to Our Queries<br />

205

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

Saved successfully!

Ooh no, something went wrong!