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

AW00000227 43662 2007-10-06 00:00:00.000 755 Road-450 Red, 60<br />

1 874.7940<br />

0.0000 874.794000<br />

(51 rows affected)<br />

C:\><br />

How It Works<br />

We started out by bundling the <strong>SQL</strong> commands we would need into a single script — first, the USE command,<br />

and then the actual SELECT statement.<br />

We then executed our statement using sqlcmd. The –U and –P commands provided the login username<br />

and password information just as they did earlier in the chapter. The –i parameter told sqlcmd that we<br />

had an input file, and we included that file name immediately following the –i parameter. Finally, we<br />

included the –o parameter to tell sqlcmd that we wanted the output written to a file (we, of course, then<br />

provided a file name — YesterdaysOrders.txt). Don’t get confused by the two files both named<br />

YesterdaysOrders — they are separate files with the .sql and .txt files separating what their particular<br />

use is for.<br />

There is a wide variety of different parameters for sqlcmd, but the most important are the login, the password,<br />

and the one that says what you want to do (straight query or input file). You can mix and match many of these<br />

parameters to obtain fairly complex behavior from this seemingly simple command-line tool.<br />

Dynamic <strong>SQL</strong>: Generating Y our Code On<br />

the Fly with the EXEC Command<br />

OK, so all this saving stuff away in scripts is all fine and dandy, but what if you don’t know what code<br />

you need to execute until runtime?<br />

As a side note, notice that we are done with sqlcmd for now — the following examples should be run<br />

utilizing the Management Console.<br />

<strong>SQL</strong> <strong>Server</strong> allows us, with a few gotchas, to build our <strong>SQL</strong> statement on-the-fly using string manipulation.<br />

The need to do this usually stems from not being able to know the details about something until<br />

runtime. The syntax looks like this:<br />

Or:<br />

344<br />

EXEC ({|’’})<br />

EXECUTE ({|’’})<br />

As with executing a stored proc, whether you use the EXEC or EXECUTE makes no difference.

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

Saved successfully!

Ooh no, something went wrong!