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.

Out of the condition from inner condition, but still<br />

part of first block<br />

END --First block of code ends here<br />

ELSE<br />

BEGIN<br />

Statement that executes if expression is FALSE<br />

Additional statements<br />

...<br />

...<br />

Still going with statements from FALSE expression<br />

END<br />

Chapter 11: Writing Scripts and Batches<br />

Notice our ability to nest blocks of code. In each case, the inner blocks are considered to be part of the<br />

outer block of code. I have never heard of there being a limit to how many levels deep you can nest your<br />

BEGIN...END blocks, but I would suggest that you minimize them. There are definitely practical limits<br />

to how deep you can keep them readable — even if you are particularly careful about the formatting of<br />

your code.<br />

Just to put this notion into play, let’s make yet another modification to table creation. This time, we’re<br />

going to provide an informational message regardless of whether the table was created or not.<br />

-- This time we’re adding a check to see if the table DOES already exist<br />

-- We’ll remove it if it does so that the rest of our example can test the<br />

-- IF condition. Just remove this first IF EXISTS block if you want to test<br />

-- the ELSE condition below again.<br />

IF EXISTS (<br />

SELECT s.name AS SchemaName, t.name AS TableName<br />

FROM sys.schemas s<br />

JOIN sys.tables t<br />

ON s.schema_id = t.schema_id<br />

WHERE s.name = ‘dbo’<br />

AND t.name = ‘OurIFTest’<br />

)<br />

DROP TABLE OurIFTest;<br />

-- Now we’re run our conditional CREATE statement<br />

IF NOT EXISTS (<br />

SELECT s.name AS SchemaName, t.name AS TableName<br />

FROM sys.schemas s<br />

JOIN sys.tables t<br />

ON s.schema_id = t.schema_id<br />

WHERE s.name = ‘dbo’<br />

AND t.name = ‘OurIFTest’<br />

)<br />

BEGIN<br />

PRINT ‘Table dbo.OurIFTest not found.’;<br />

PRINT ‘CREATING: Table dbo.OurIFTest’;<br />

CREATE TABLE OurIFTest(<br />

Col1 int PRIMARY KEY<br />

);<br />

END<br />

ELSE<br />

PRINT ‘WARNING: Skipping CREATE as table already exists’;<br />

353

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

Saved successfully!

Ooh no, something went wrong!