Using @@identity or output when inserting into SQL Server view?

和自甴很熟 提交于 2021-02-08 03:43:04

问题


(forgive me - I'm new to both StackOverflow & SQL) Tl;dr - When using @@identity (or any other option such as scope_identity or output variable), is it possible to also use a view? Here is an example of a stored procedure using @@identity:

--SNIP--
DECLARE @AID INT
DECLARE @BID INT


INSERT INTO dbo.A (oct1)
VALUES
(@oct1)

SELECT @AID = @@IDENTITY;

INSERT INTO dbo.B (duo1)
VALUES
(@duo2)

SELECT @BID = @@IDENTITY

INSERT INTO dbo.tblAB (AID, BID)
VALUES
(@AID, @BID)
GO

Longer:

When inserting into a table, you can capture the current value of the identity seed using @@identity. This is useful if you want to insert into table A and B, capture the identity value, then insert into table AB relating A to B. Obviously this is for purposes of data normalization.

Let's say you were to abstract the DB Schema with a few that performs inner joins on your tables to make the data easier to work with. How would you populate the cross reference tables properly in that case? Can it be done the same way, if so, how?


回答1:


Avoid using @@IDENTITY or SCOPE_IDENTITY() if your system is using Parallel plans as there is a nasty bug. Please refer - http://connect.microsoft.com/SQL/feedback/ViewFeedback.aspx?FeedbackID=328811

Better way to fetch the inserted Identity ID would be to use OUTPUT clause.

CREATE TABLE tblTest
(         
    Sno         INT IDENTITY(1,1) NOT NULL,         
    FirstName   VARCHAR(20) 
)  

DECLARE @pk TABLE (ID INT)  

INSERT INTO tblTest(FirstName) 
OUTPUT INSERTED.Sno INTO @pk
SELECT 'sample' 

SELECT * FROM @pk 

EDIT:

It would work with Views as well. Please see the sample below. Hope this is what you were looking for.

CREATE VIEW v1
AS
SELECT sno, firstname FROM tbltest
GO

DECLARE @pk TABLE (ID INT)  

INSERT INTO v1(FirstName) 
OUTPUT INSERTED.Sno INTO @pk
SELECT 'sample' 

SELECT ID FROM @pk



回答2:


@@IDENTITY returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value.

SCOPE_IDENTITY() returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well

Although the issue with either of these is fixed by microsoft , I would suggest you should go with "OUTPUT", and yes, it can be used with view as well



来源:https://stackoverflow.com/questions/11534500/using-identity-or-output-when-inserting-into-sql-server-view

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