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

key on another table (the parent). So what we have is a situation where the two child tables need to get<br />

their key from the parent. Therefore, we need to insert a record into the parent first, and then retrieve the<br />

identity value generated so we can make use of it in the other tables.<br />

Try It Out Using @@IDENTITY<br />

332<br />

Now that we have some tables to work with, we’re ready to try a little test script:<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 />

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

/* The next line is going to blow up because the one column in<br />

** the table is the primary key, and primary keys can’t be set<br />

** to NULL. @@IDENTITY will be NULL because we just issued an<br />

** INSERT statement a few lines ago, and the table we did the<br />

** INSERT into doesn’t have an identity field. Perhaps the biggest<br />

** thing to note here is when @@IDENTITY changed - right after<br />

** the next INSERT statement. */<br />

INSERT INTO TestChild2<br />

VALUES<br />

(@@IDENTITY);

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

Saved successfully!

Ooh no, something went wrong!