SQL 使用 Select 插入并输出以创建临时副本 table

SQL Insert with Select and OUTPUT to create a temp copy table

如何制作插入记录的副本并保留其复制记录的原始 ID 并将其放入 Temp table。 当我将 Docs.DocID 添加到我得到的输出中时。 "The multi-part identifier "Docs.DocID”无法绑定。”

DECLARE @CopiedDocIDs TABLE(NewDocID int, CurrentDocID int)

INSERT INTO Docs (Filename,Backup)
OUTPUT INSERTED.DocID, Docs.DocID INTO @CopiedDocIDs 
SELECT Filename, 1
FROM Docs 
WHERE Filename like 'MyDoc%'

哦,是的,我正在使用:Microsoft SQL Server 2005 - 9.00.4035.00 (X64)

编辑: 好吧有点乱,但它确实有效。这是有效的,但我将在 RowKey 中添加另一列,只是确保它是唯一的。

DECLARE @Docs TABLE (DocID int IDENTITY(1, 1), [FileName] varchar(10), FileDate datetime)
INSERT INTO @Docs VALUES('Doc1','01-01-2011 12:21:12:003')
INSERT INTO @Docs VALUES('Doc2','01-01-2013 02:41:32:120')
INSERT INTO @Docs VALUES('Doc3','01-01-2014 09:30:12:023')
INSERT INTO @Docs VALUES('Doc','01-01-2014 09:30:12:111')
INSERT INTO @Docs VALUES('Doc','01-01-2014 09:30:15:123')

DECLARE @NewDocIDs TABLE(NewDocID int, CopyDocID int, RowKey Varchar(50))

INSERT INTO @Docs ([FileName],FileDate)
OUTPUT INSERTED.DocID, null, (INSERTED.[FileName]+'-'+CONVERT(varchar(50),INSERTED.FileDate,126)) INTO @NewDocIDs
SELECT [FileName],FileDate
FROM @Docs 

UPDATE @NewDocIDs SET CopyDocID=(SELECT TOP 1 DocID FROM @Docs WHERE [FileName]+'-'+CONVERT(varchar(50),FileDate,126)=RowKey) 

select * from @Docs
select * from @NewDocIDs --## output I need

您只能为 OUTPUT 语句使用 inserted (or deleted) 值。

但是这个 MERGE 声明可能正是您所需要的。

MERGE INTO Docs
USING Docs AS dc
ON 1 = 0
WHEN NOT MATCHED THEN
  INSERT(Filename, Backup) Values(dc.Filename, 1)
OUTPUT inserted.DocID, dc.DocID INTO 
  @CopiedDocIDs(NewDocID, CurrentDocID)

但不幸的是 MERGE 用于 SQL 服务器 >2008

这在 2005 年是不可能的。您所能做的就是向文档添​​加列 table:

Alter table Docs Add OriginalDocID int null;
GO

DECLARE @CopiedDocIDs TABLE(NewDocID int, CurrentDocID int)

INSERT INTO Docs (Filename,Backup,OriginalDocID)
OUTPUT INSERTED.DocID, INSERTED.OriginalDocID INTO @CopiedDocIDs 
SELECT Filename, 1, DocID
FROM Docs 
WHERE Filename like 'MyDoc%'

如果您有 >=2008,那么 MERGE 语句将有所帮助:

DECLARE @CopiedDocIDs TABLE(NewDocID int, CurrentDocID int)

MERGE INTO Docs AS TGT
USING(SELECT DocID, Filename
FROM Docs 
WHERE Filename like 'MyDoc%') AS SRS
ON 1 = 0
WHEN NOT MATCHED THEN INSERT VALUES(SRS.FileName, 1)
OUTPUT Inserted.DocID, SRS.DocID;