当前插入行的标识
我正在开发一个项目,出现了一个问题:插入语句可以将它自己的标识插入到另一个字段中吗?
这个想法是,记录将按层次结构排列,“父”字段将指向父记录的 ID,而给定树的“顶部”记录将仅指向其自身。
当然,我们可以将其保留为空,或者稍后返回并插入其 ID。但我想知道在插入记录时是否有任何 SQL Server 操作将 IDENTITY 插入到另一个字段中?
编辑:或者有没有办法将一个字段的默认值指定为另一个字段的值?这也将解决这个问题。
编辑:默认字段是另一个字段似乎已经得到回答,答案是否定的,请使用触发器。当然,这对解决约束和非空字段的问题没有帮助。 (http://social.msdn.microsoft.com/Forums/en/sqltools/thread/661d3dc8-b053-47b9-be74-302ffa11bf76)
I'm working on a project and the question came up: Can an insert statement insert it's own identity in to another field?
The idea is that there would be a hierarchical arrangement of records and that the 'parent' field would point to the ID of the parent record and that the 'top' record for a given tree would just point to itself.
We could of course just leave it null for the parent or come back and insert its ID later. But I was wondering if there was any SQL Server operation to insert an IDENTITY in to another field as the record is being inserted?
EDIT: Or is there a way to specify the default value for a field to be the value of another field? That would also address the issue.
EDIT: The default field being another field has already been answered it seems, and the answer is no, use a trigger. Of course, that doesn't help the issue of constraints and non-null fields. (http://social.msdn.microsoft.com/Forums/en/sqltools/thread/661d3dc8-b053-47b9-be74-302ffa11bf76)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
否。对于这种层次结构,除非您使用
SET IDENTITY_INSERT ON
插入显式ID
值,否则您需要首先插入顶层并使用SCOPE_IDENTITY
> 或OUTPUT
子句来获取插入的ID
以便用于下一个级别。No. For this kind of hierarchy unless you are inserting explicit
ID
values withSET IDENTITY_INSERT ON
you would need to insert the top level first and useSCOPE_IDENTITY
or theOUTPUT
clause to get the insertedID
s to use for the next level down.在某种程度上你可以。插入允许 OUTPUT 子句,并且 OUTPUT 可以重定向到一个表中可以是与您当前插入的表相同的表。下面的示例插入一个父节点,但它也会自动插入一个子节点,该子节点在插入期间将parent_id设置为新生成的ID:
但我最终没有看到任何实际用途,这更像是一个表演帽子戏法。
To a certain degree you can. Insert allows for OUTPUT clause and the OUTPUT can be redirected INTO a table which can be the same table as the one you're currently inserting into. The following example inserts a parent node but it also automatically inserts a child node which has the parent_id set to the newly generated ID during insert:
I don't see any practical use in the end though, this is more of a show hat-trick.