0

我有一个场景,我必须使用脚本将一些主数据插入到表中,以便我们可以在部署时在生产服务器上使用这个脚本。

我的桌子是

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

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

现在我在excel中有一些用于类别和类别类型的行数据。我必须生成数据脚本(一组插入语句)。

我做了什么

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

我只想知道有什么办法可以避免 identity_insert ON/OFF 的事情。

4

1 回答 1

1

可能这就是你要找的东西:

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

希望它可以帮助
最好的问候,
Iordan

于 2011-12-16T15:23:35.463 回答