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.

-- This won’t work<br />

DECLARE @NumberOfLetters int = 15;<br />

EXEC(‘SELECT LEFT(Name,’ + CAST(@NumberOfLetters AS varchar) + ‘) AS ShortName<br />

FROM Production.Product’);<br />

GO<br />

-- But this does<br />

DECLARE @NumberOfLetters AS int = 15;<br />

DECLARE @str AS varchar(255);<br />

SET @str = ‘SELECT LEFT(Name,’ + CAST(@NumberOfLetters AS varchar) + ‘) AS ShortName<br />

FROM Production.Product’;<br />

EXEC(@str);<br />

The first instance gets an error message because the CAST function needs to be fully resolved prior to the<br />

EXEC line:<br />

Msg 102, Level 15, State 1, Line 9<br />

Incorrect syntax near ‘CAST’.<br />

But the second line works just fine because it is already a complete string:<br />

ShortName<br />

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

Adjustable Race<br />

All-Purpose Bik<br />

AWC Logo Cap<br />

...<br />

...<br />

Women’s Tights,<br />

Women’s Tights,<br />

Women’s Tights,<br />

EXEC and UDFs<br />

This is a tough one to touch on because we haven’t gotten to user-defined functions as yet, but suffice to<br />

say that you are not allowed to use EXEC to run dynamic <strong>SQL</strong> within a UDF — period. (EXEC to run a<br />

sproc is, however, legal in a few cases.)<br />

Control-of-Flow Statements<br />

Control-of-flow statements are a veritable must for any programming language these days. I can’t imagine<br />

having to write my code where I couldn’t change what commands to run depending on a condition.<br />

T-<strong>SQL</strong> offers most of the classic choices for control of flow situations, including:<br />

❑ IF ... ELSE<br />

❑ GOTO<br />

❑ WHILE<br />

❑ WAITFOR<br />

❑ TRY/CATCH<br />

Chapter 11: Writing Scripts and Batches<br />

349

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

Saved successfully!

Ooh no, something went wrong!