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

This should take you down to a blank line (with no prompt of any kind), where you can enter in this:<br />

SELECT * FROM AdventureWorks<strong>2008</strong>.Production.Location<br />

Then press F6 and Return (this ends the creation of our text file). You should get back a message like:<br />

1 file(s) copied.<br />

Now let’s retry our earlier query using a script file this time. The command line at the prompt has only a<br />

slight change to it:<br />

C:\>sqlcmd -Usa -Pmypass -i testsql.sql<br />

This should get us exactly the same results as we had when we ran the query using -Q. The major difference<br />

is, of course, that we took the command from a file. The file could have had hundreds — if not<br />

thousands — of different commands in it.<br />

Try It Out Generating a Text File with sqlcmd<br />

342<br />

As a final example of sqlcmd, let’s utilize it to generate a text file that we might import into another<br />

application for analysis (Excel for example).<br />

Back in Chapter 10, we created a view that listed yesterday’s orders for us. First, we’re going to take the<br />

core query of that view, and stick it into a text file:<br />

C:\copy con YesterdaysOrders.sql<br />

This should again take you down to a blank line (with no prompt of any kind), where you can enter this:<br />

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

SELECT sc.AccountNumber,<br />

soh.SalesOrderID,<br />

soh.OrderDate,<br />

sod.ProductID,<br />

pp.Name,<br />

sod.OrderQty,<br />

sod.UnitPrice,<br />

sod.UnitPriceDiscount * sod.UnitPrice * sod.OrderQty AS TotalDiscount,<br />

sod.LineTotal<br />

FROM Sales.Customer AS sc<br />

INNER JOIN Sales.SalesOrderHeader AS soh<br />

ON sc.CustomerID = soh.CustomerID<br />

INNER JOIN Sales.SalesOrderDetail AS sod<br />

ON soh.SalesOrderID = sod.SalesOrderID<br />

INNER JOIN Production.Product AS pp<br />

ON sod.ProductID = pp.ProductID<br />

WHERE CAST(soh.OrderDate AS Date) =<br />

CAST(DATEADD(day,-1,GETDATE()) AS Date)<br />

Again press F6 and press Enter to tell Windows to save the file for you.

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

Saved successfully!

Ooh no, something went wrong!