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.

Chapter 11: Writing Scripts and Batches<br />

ELSE<br />

PRINT ‘The value currently in @@IDENTITY is ‘ + CONVERT(varchar(2),@@IDENTITY);<br />

-- The next line is just a spacer for our print out<br />

PRINT ‘’;<br />

/* This time all will go fine because we are using the value that<br />

** we have placed in safekeeping instead of @@IDENTITY directly.*/<br />

INSERT INTO TestChild2<br />

VALUES<br />

(@Ident);<br />

This time everything runs just fine:<br />

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

The value we got originally from @@IDENTITY was 1<br />

The value currently in @@IDENTITY is 1<br />

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

The value we got originally from @@IDENTITY was 1<br />

The value currently in @@IDENTITY is NULL<br />

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

Using @@ROWCOUNT<br />

334<br />

In this example, it was fairly easy to tell that there was a problem because of the<br />

attempt at inserting a NULL into the primary key. Now, imagine a far less pretty scenario<br />

— one where the second table did have an identity column. You could easily<br />

wind up inserting bogus data into your table and not even knowing about it — at<br />

least not until you already had a very serious data integrity problem on your hands!<br />

In the many queries that we ran up to this point, it’s always been pretty easy to tell how many rows a<br />

statement affected — the Query window tells us. For example, if we run:<br />

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

SELECT * FROM Person.Person;<br />

then we see all the rows in Person, but we also see a count on the number of rows affected by our query<br />

(in this case, it’s all the rows in the table):<br />

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

But what if we need to programmatically know how many rows were affected? Much like @@IDENITY,<br />

@@ROWCOUNT is an invaluable tool in the fight to know what’s going on as your script runs — but this<br />

time the value is how many rows were affected rather than our identity value.<br />

Let’s examine this just a bit further with an example:<br />

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

GO

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

Saved successfully!

Ooh no, something went wrong!