views:

31

answers:

1

Thanks everyone for the feedback

Hi All,

I'm am trying to create a stored procedure that does two inserts into two different tables.

DECLARE @New_Group1_Id
DECLARE @New_Group2_Id

INSERT INTO Group1
                      (Group1_Desc)
VALUES     (N'Indianapolis')

SELECT @New_Group1_Id = Scope_Identity()


INSERT INTO Group2
                      (Group2_Desc)
VALUES     (N'Indianapolis')

SELECT @New_Group2_Id = Scope_Identity()

The results show 1 and 2 for Ids instead of 1 and 1 (if these were the first records ever to be inserted in the table)

Is there a way to get the IDENTITY values for each insert statement? I've tried using Scope_Identity() but the results Thanks,

+3  A: 

you probably deleted rows in one of the table, truncate the table instead (which will reset the identity) and try again or reseed the table DBCC CHECKIDENT (Group1, RESEED, 0);

here run this to verify that it works as expected

Create table Group1(id int identity,Group1_Desc nvarchar(100)) 
create table Group2(id int identity,Group2_Desc nvarchar(100)) 

DECLARE @New_Group1_Id int
DECLARE @New_Group2_Id int

INSERT INTO Group1(Group1_Desc)
VALUES     (N'Indianapolis')

SELECT @New_Group1_Id = Scope_Identity()


INSERT INTO Group2 (Group2_Desc)
VALUES     (N'Indianapolis')

SELECT @New_Group2_Id = Scope_Identity()

select @New_Group1_Id,@New_Group2_Id

now do this

delete Group1

now run again

DECLARE @New_Group1_Id int
DECLARE @New_Group2_Id int

INSERT INTO Group1(Group1_Desc)
VALUES     (N'Indianapolis')

SELECT @New_Group1_Id = Scope_Identity()


INSERT INTO Group2 (Group2_Desc)
VALUES     (N'Indianapolis')

SELECT @New_Group2_Id = Scope_Identity()

select @New_Group1_Id,@New_Group2_Id

and you will see that both are 2

now truncate the table group1

truncate table Group1

run this again and you will get 1 and 3

DECLARE @New_Group1_Id int
DECLARE @New_Group2_Id int

INSERT INTO Group1(Group1_Desc)
VALUES     (N'Indianapolis')

SELECT @New_Group1_Id = Scope_Identity()


INSERT INTO Group2 (Group2_Desc)
VALUES     (N'Indianapolis')

SELECT @New_Group2_Id = Scope_Identity()

select @New_Group1_Id,@New_Group2_Id
SQLMenace
I have the above wrapped in a transaction rollback block and I don't understand why if it's rolling back the transaction why are the identities still increasing each time I run it.
rod
because a rollback is a delete, this is normal behavior..the identity value was reserved for that insert
SQLMenace
thanks for the insight
rod