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.

How It Works<br />

What we’re doing in this script is seeing what happens if we depend on @@IDENTITY directly rather<br />

than moving the value to a safe place. When we execute the preceding script, everything’s going to work<br />

just fine until the final INSERT. That final statement is trying to make use of @@IDENTITY directly, but<br />

the preceding INSERT statement has already changed the value in @@IDENTITY. Because that statement<br />

is on a table with no identity column, the value in @@IDENTITY is set to NULL. Because we can’t have a<br />

NULL value in our primary key, the last INSERT fails:<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 />

Msg 515, Level 16, State 2, Line 41<br />

Cannot insert the value NULL into column ‘IDcol’, table<br />

‘Accounting.dbo.TestChild2’; column does not allow nulls. INSERT fails.<br />

The statement has been terminated.<br />

If we make just one little change (to save the original @@IDENTITY value):<br />

/*****************************************<br />

** This script illustrates how the identity<br />

** value gets lost as soon as another INSERT<br />

** happens<br />

****************************************** */<br />

DECLARE @Ident int; -- This will be a holding variable<br />

/* We’ll use it to show how we can<br />

** move values from system functions<br />

** into a safe place.<br />

*/<br />

INSERT INTO TestIdent<br />

DEFAULT VALUES;<br />

SET @Ident = @@IDENTITY;<br />

PRINT ‘The value we got originally from @@IDENTITY was ‘ +<br />

CONVERT(varchar(2),@Ident);<br />

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

/* On this first INSERT using @@IDENTITY, we’re going to get lucky.<br />

** We’ll get a proper value because there is nothing between our<br />

** original INSERT and this one. You’ll see that on the INSERT that<br />

** will follow after this one, we won’t be so lucky anymore. */<br />

INSERT INTO TestChild1<br />

VALUES<br />

(@@IDENTITY);<br />

PRINT ‘The value we got originally from @@IDENTITY was ‘ +<br />

CONVERT(varchar(2),@Ident);<br />

IF (SELECT @@IDENTITY) IS NULL<br />

PRINT ‘The value currently in @@IDENTITY is NULL’;<br />

Chapter 11: Writing Scripts and Batches<br />

333

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

Saved successfully!

Ooh no, something went wrong!