I use bellow code to archive old data in ArchiveTable
and delete archived data from SourceTable
DELETE FROM SourceTable
OUTPUT
DELETED.[ID],
DELETED.[Code],
DELETED.[Title]
INTO ArchiveTable([OldID], [Code], [Title])
WHERE Condition
Structure of tables:
CREATE TABLE [SourceTable](
[ID] [INT] IDENTITY(1,1) NOT NULL,
[Code] [VARCHAR](16) NULL,
[Title] [NVARCHAR](128) NULL,
CONSTRAINT [PK_SourceTable] PRIMARY KEY CLUSTERED ([ID] ASC)
)
GO
CREATE TABLE [ArchiveTable](
[ID] [INT] IDENTITY(1,1) NOT NULL,
[OldID] [INT] NOT NULL,
[Code] [VARCHAR](16) NULL,
[Title] [NVARCHAR](128) NULL,
CONSTRAINT [PK_ArchiveTable] PRIMARY KEY CLUSTERED ([ID] ASC)
)
GO
I need to return deleted records and ArchiveTable.[ID]
to application. I change the code like this:
DELETE FROM SourceTable
OUTPUT
DELETED.[ID],
DELETED.[Code],
DELETED.[Title]
INTO ArchiveTable([OldID], [Code], [Title])
OUTPUT DELETED.*
WHERE Condition
This code return deleted records but I don't know how to get ID of ArchiveTable
for this records. Look at ArchiveTable
structure, It has OldID
column that refer to SourceTable.ID
and ID
column that it is an Identity
column of ArchiveTable
. I need to ArchiveTable.ID
in final result.
3条答案
按热度按时间lmyy7pcs1#
You can use a temporary table
A variant with a table variable
xqkwcwgp2#
I found an interesting variant using
DML
withOUTPUT
inSP
andINSERT...EXEC...
after that:Test tables:
DML procedures:
Tests:
Maybe it'll be interesting to someone.
ttygqcqt3#
I encountered the same issue and this resolved it. First make sure you set this on the target table;
And then define all the columns in both the DELETED section and the INTO list;