0

I am having a scenario where I have to insert some master data into the table with script, so that we can this script on production server while deployment.

My tables are

Category
 --Id (PK, Identity)
 --Name

CategoryType
  --Id (PK, Identity)
  --Name
  --CategoryID (FK) 

Now I have some row data in excel for category and categorytype. I have to generate the data script (bunch of insert statement).

What I did

Start with  identity_insert ON 
insert statement for Category table
Insert statement for CategoryType table with respect of category PK
end  identity_insert Off

I just want to know Is there any way I can avoid identity_insert ON/OFF thing.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
Mahesh
  • 1,754
  • 7
  • 36
  • 54

1 Answers1

1

may be this is what you are looking for:

DECLARE @inserted table ( id int ) --assuming ID is int

INSERT INTO Category ( Name )
OUTPUT INSERTED.Id INTO @inserted
VALUES( 'MyCategory Name' )

INSERT INTO CategoryType( Name, CategoryID )
SELECT id, 'MyCategoryTypeName'
FROM @inserted

Hope it helps
Best Regards,
Iordan

IordanTanev
  • 6,130
  • 5
  • 40
  • 49