views:

634

answers:

2

The MSDN docs weren't entirely clear on this one. or perhaps I'm not reading them well enough.

If I do an insert (which may insert zero rows), followed by

;SELECT SCOPE_IDENTITY()

And then call the command by ExecuteScalar()...

What will the result be if the Insert doesn't insert any rows?

I want to stop if it fails so that I don't continue on inserting child records to a bad, or wrong parent ID.

+4  A: 

If no Identity is inserted SCOPE_IDENTITY() will return null, you can check for the condition you specify by assigning SCOPE_IDENTITY() to a variable and then checking the variables contents.

Illustration

Create Proc SomeInsertToFail(@ID int OUTPUT)
as
Begin
    Select @ID =  Scope_Identity()
End
Declare @SOMEID int
Exec SomeInsertToFail @SOMEID OUTPUT
Select @SOMEID  --This will yield null
cmsjr
so can I do SELECT IsNull(Scope_Identity(), -1) so that I always get a valid INT and the fail value cant be an actual ID? (assuming of course my identity starts at 1)
Neil N
might be worth testing on some more esoteric scenarios... INSERT on a table where a trigger maintains integrity and raises an error to prevent the insert...
Dems
@Dems, thats a interesting test, I will give it a try.
Neil N
+2  A: 

NULL

source: did a SELECT scope_identity() on a blank query (aka no insert)

jfrobishow