On SQL INSERT can I use the identity column for part of the insert data in another column at the same time?

风格不统一 提交于 2019-12-04 05:26:46

问题


CREATE TABLE Table1 :
Id int IDENTITY(1,1),
PK_Column1 nvarchar(50) Primary Key.

INSERT INTO Table1 (PK_Column1) VALUES ('Name'+Id)

Result:

Id  PK_Column1
1   Name1

Is this possible? Or do I need to manage the Id column myself for this to work?


回答1:


From the documentation:

After an INSERT, SELECT INTO, or bulk copy statement completes, @@IDENTITY contains the last identity value generated by the statement.

This applies to all the other identity checkers.

You should probably write a little SP to update the record immediately after your insert if this is what you need. Given that your primary_key appears to be some unusual composite of the ID and a varchar, you would also be best reviewing your data model.

It's important to note the difference with @@IDENTITY and SCOPE_IDENTITY():

@@IDENTITY and SCOPE_IDENTITY return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.



来源:https://stackoverflow.com/questions/17291595/on-sql-insert-can-i-use-the-identity-column-for-part-of-the-insert-data-in-anoth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!