使用Select和OUTPUT插入SQL以创建临时副本表

时间:2015-02-20 05:27:01

标签: sql sql-server sql-server-2005

如何制作插入记录的副本并保留其复制的记录的原始ID并将其放入Temp表中。 当我将Docs.DocID添加到OUTPUT时,我得到了。 "多部分标识符" 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

enter image description here

2 个答案:

答案 0 :(得分:2)

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

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;

答案 1 :(得分:1)

您只能对inserted (or deleted)声明使用OUTPUT值。

但是这个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 Server> 2008