在没有identity_insert ON的情况下在关系表中插入数据

发布于 2024-12-21 11:45:24 字数 508 浏览 4 评论 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 的事情。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人 2024-12-28 11:45:24

可能这就是您正在寻找的:

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

希望它有帮助
最好的问候,
约丹

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文