将自动生成的ID作为外键插入另一个表 [英] Insert automatic generate id as foreign key to another table

查看:262
本文介绍了将自动生成的ID作为外键插入另一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从SQL Server插入生成ID作为另一个表的外键.发生此错误``当IDENTITY_INSERT设置为OFF时,无法为表''Kursus''中的身份列插入显式值.''

我该如何解决这个问题.谢谢

how can i insert generate id from SQL server as foreign key to another table. This error has occur ''Cannot insert explicit value for identity column in table ''Kursus'' when IDENTITY_INSERT is set to OFF.''

How i can solve this problem. Thank You

推荐答案

在具有标识字段的表中插入一行时,您根本不会在insert语句中提及此字段.例如,您有一个包含两列的表:
-ID(身份)
-名称(varchar)

插入语句可能看起来像
When you insert a row to a table which has an identity field, you don''t mention this field in the insert statement at all. For example, you have a table with two columns:
- Id (identity)
- Name (varchar)

The insert statement could look like
INSERT INTO INTO TableName (Name) VALUES (''Some name'');


插入后,您可以使用 SCOPE_IDENTITY [


After the insert you can use SCOPE_IDENTITY[^] to get the value of the inserted Id so you can use the value for a foreign key in some other insert into a child table.


该错误消息表示您尝试执行与问题中所写内容不同的内容.如果您尝试为INSERT语句中的自动生成的ID字段指定一个值,则会收到此错误.可以这样做,但是您必须将IDENTITY_INSERT设置为ON,这将允许您为自动生成的字段指定一个值(通常不建议使用,除非极少数情况).

干杯!
The error message implies that your trying to do something different from what you wrote in your question. You receive this error if you try to specify a value for an autogenerated ID field in an INSERT statement. It is possible to do that but you''d have to set IDENTITY_INSERT to ON, which will allow you to specify a value for an autogenerated field (generally not advisable except in rare circumstances).

Cheers!


这篇关于将自动生成的ID作为外键插入另一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆